helia 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +97 -1
- package/dist/src/helia.d.ts +11 -4
- package/dist/src/helia.d.ts.map +1 -1
- package/dist/src/helia.js +27 -59
- package/dist/src/helia.js.map +1 -1
- package/dist/src/index.d.ts +13 -8
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +16 -9
- package/dist/src/index.js.map +1 -1
- package/dist/src/pins.d.ts +3 -3
- package/dist/src/pins.d.ts.map +1 -1
- package/dist/src/pins.js +59 -64
- package/dist/src/pins.js.map +1 -1
- package/dist/src/storage.d.ts +5 -5
- package/dist/src/storage.d.ts.map +1 -1
- package/dist/src/storage.js +5 -1
- package/dist/src/storage.js.map +1 -1
- package/dist/src/utils/dag-walkers.d.ts.map +1 -1
- package/dist/src/utils/dag-walkers.js +2 -1
- package/dist/src/utils/dag-walkers.js.map +1 -1
- package/dist/src/utils/datastore-version.d.ts +1 -1
- package/dist/src/utils/datastore-version.d.ts.map +1 -1
- package/dist/src/utils/datastore-version.js.map +1 -1
- package/dist/src/utils/libp2p.browser.d.ts +9 -0
- package/dist/src/utils/libp2p.browser.d.ts.map +1 -0
- package/dist/src/utils/libp2p.browser.js +65 -0
- package/dist/src/utils/libp2p.browser.js.map +1 -0
- package/dist/src/utils/libp2p.d.ts +15 -0
- package/dist/src/utils/libp2p.d.ts.map +1 -0
- package/dist/src/utils/libp2p.js +64 -0
- package/dist/src/utils/libp2p.js.map +1 -0
- package/package.json +25 -11
- package/src/helia.ts +34 -55
- package/src/index.ts +25 -10
- package/src/pins.ts +13 -13
- package/src/storage.ts +12 -11
- package/src/utils/dag-walkers.ts +2 -2
- package/src/utils/datastore-version.ts +1 -1
- package/src/utils/libp2p.browser.ts +68 -0
- package/src/utils/libp2p.ts +72 -0
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,99 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Helia=(()=>{var Ku=Object.create;var gr=Object.defineProperty;var Xu=Object.getOwnPropertyDescriptor;var Ju=Object.getOwnPropertyNames;var Zu=Object.getPrototypeOf,Yu=Object.prototype.hasOwnProperty;var S=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),V=(r,e)=>{for(var t in e)gr(r,t,{get:e[t],enumerable:!0})},xo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ju(e))!Yu.call(r,i)&&i!==t&&gr(r,i,{get:()=>e[i],enumerable:!(n=Xu(e,i))||n.enumerable});return r};var U=(r,e,t)=>(t=r!=null?Ku(Zu(r)):{},xo(e||!r||!r.__esModule?gr(t,"default",{value:r,enumerable:!0}):t,r)),el=r=>xo(gr({},"__esModule",{value:!0}),r);var Ho=S((bp,Wo)=>{Wo.exports=$o;var zo=128,zl=127,$l=~zl,Wl=Math.pow(2,31);function $o(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Wl;)e[t++]=r&255|zo,r/=128;for(;r&$l;)e[t++]=r&255|zo,r>>>=7;return e[t]=r|0,$o.bytes=t-n+1,e}});var jo=S((_p,Vo)=>{Vo.exports=jn;var Hl=128,qo=127;function jn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw jn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&qo)<<i:(s&qo)*Math.pow(2,i),i+=7}while(s>=Hl);return jn.bytes=o-n,t}});var Qo=S((vp,Go)=>{var ql=Math.pow(2,7),Vl=Math.pow(2,14),jl=Math.pow(2,21),Gl=Math.pow(2,28),Ql=Math.pow(2,35),Kl=Math.pow(2,42),Xl=Math.pow(2,49),Jl=Math.pow(2,56),Zl=Math.pow(2,63);Go.exports=function(r){return r<ql?1:r<Vl?2:r<jl?3:r<Gl?4:r<Ql?5:r<Kl?6:r<Xl?7:r<Jl?8:r<Zl?9:10}});var Xo=S((xp,Ko)=>{Ko.exports={encode:Ho(),decode:jo(),encodingLength:Qo()}});var Yo=S((kp,Zo)=>{"use strict";var Jo=Xo();Zo.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Jo.decode(r);e.push(t),r=r.slice(Jo.decode.bytes)}return e}});var rs=S((Ep,ts)=>{ts.exports=Gn;var es=128,Yl=127,ef=~Yl,tf=Math.pow(2,31);function Gn(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Gn.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=tf;)e[t++]=r&255|es,r/=128;for(;r&ef;)e[t++]=r&255|es,r>>>=7;return e[t]=r|0,Gn.bytes=t-n+1,e}});var os=S((Sp,is)=>{is.exports=Qn;var rf=128,ns=127;function Qn(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw Qn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&ns)<<i:(s&ns)*Math.pow(2,i),i+=7}while(s>=rf);return Qn.bytes=o-n,t}});var as=S((Tp,ss)=>{var nf=Math.pow(2,7),of=Math.pow(2,14),sf=Math.pow(2,21),af=Math.pow(2,28),cf=Math.pow(2,35),uf=Math.pow(2,42),lf=Math.pow(2,49),ff=Math.pow(2,56),hf=Math.pow(2,63);ss.exports=function(r){return r<nf?1:r<of?2:r<sf?3:r<af?4:r<cf?5:r<uf?6:r<lf?7:r<ff?8:r<hf?9:10}});var us=S((Ap,cs)=>{cs.exports={encode:rs(),decode:os(),encodingLength:as()}});var hs=S((Cp,fs)=>{var mt=1e3,yt=mt*60,gt=yt*60,Ge=gt*24,pf=Ge*7,mf=Ge*365.25;fs.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return yf(r);if(t==="number"&&isFinite(r))return e.long?wf(r):gf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function yf(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*mf;case"weeks":case"week":case"w":return t*pf;case"days":case"day":case"d":return t*Ge;case"hours":case"hour":case"hrs":case"hr":case"h":return t*gt;case"minutes":case"minute":case"mins":case"min":case"m":return t*yt;case"seconds":case"second":case"secs":case"sec":case"s":return t*mt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function gf(r){var e=Math.abs(r);return e>=Ge?Math.round(r/Ge)+"d":e>=gt?Math.round(r/gt)+"h":e>=yt?Math.round(r/yt)+"m":e>=mt?Math.round(r/mt)+"s":r+"ms"}function wf(r){var e=Math.abs(r);return e>=Ge?_r(r,e,Ge,"day"):e>=gt?_r(r,e,gt,"hour"):e>=yt?_r(r,e,yt,"minute"):e>=mt?_r(r,e,mt,"second"):r+" ms"}function _r(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ps=S((Lp,ds)=>{function bf(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=hs(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let d=0;d<l.length;d++)h=(h<<5)-h+l.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l){let h,d=null,v,y;function g(...k){if(!g.enabled)return;let I=g,O=Number(new Date),ne=O-(h||O);I.diff=ne,I.prev=h,I.curr=O,h=O,k[0]=t.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let $=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(ie,Q)=>{if(ie==="%%")return"%";$++;let oe=t.formatters[Q];if(typeof oe=="function"){let ut=k[$];ie=oe.call(I,ut),k.splice($,1),$--}return ie}),t.formatArgs.call(I,k),(I.log||t.log).apply(I,k)}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:()=>d!==null?d:(v!==t.namespaces&&(v=t.namespaces,y=t.enabled(l)),y),set:k=>{d=k}}),typeof t.init=="function"&&t.init(g),g}function n(l,h){let d=t(this.namespace+(typeof h>"u"?":":h)+l);return d.log=this.log,d}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,d=(typeof l=="string"?l:"").split(/[\s,]+/),v=d.length;for(h=0;h<v;h++)d[h]&&(l=d[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(l))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ds.exports=bf});var ms=S((K,vr)=>{K.formatArgs=vf;K.save=xf;K.load=kf;K.useColors=_f;K.storage=Ef();K.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`."))}})();K.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 _f(){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 vf(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vr.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)}K.log=console.debug||console.log||(()=>{});function xf(r){try{r?K.storage.setItem("debug",r):K.storage.removeItem("debug")}catch{}}function kf(){let r;try{r=K.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Ef(){try{return localStorage}catch{}}vr.exports=ps()(K);var{formatters:Sf}=vr.exports;Sf.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var gs=S((jp,ys)=>{"use strict";ys.exports=Lf;function Lf(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,o=!0;i<arguments.length;)t[n++]=arguments[i++];return new Promise(function(a,c){t[n]=function(l){if(o)if(o=!1,l)c(l);else{for(var h=new Array(arguments.length-1),d=0;d<h.length;)h[d++]=arguments[d];a.apply(null,h)}};try{r.apply(e||null,t)}catch(u){o&&(o=!1,c(u))}})}});var vs=S(_s=>{"use strict";var kr=_s;kr.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 bt=new Array(64),bs=new Array(123);for(he=0;he<64;)bs[bt[he]=he<26?he+65:he<52?he+71:he<62?he-4:he-59|43]=he++;var he;kr.encode=function(e,t,n){for(var i=null,o=[],s=0,a=0,c;t<n;){var u=e[t++];switch(a){case 0:o[s++]=bt[u>>2],c=(u&3)<<4,a=1;break;case 1:o[s++]=bt[c|u>>4],c=(u&15)<<2,a=2;break;case 2:o[s++]=bt[c|u>>6],o[s++]=bt[u&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=bt[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 ws="invalid encoding";kr.decode=function(e,t,n){for(var i=n,o=0,s,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&o>1)break;if((c=bs[c])===void 0)throw Error(ws);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(ws);return n-i};kr.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var ks=S((Qp,xs)=>{"use strict";xs.exports=Er;function Er(){this._listeners={}}Er.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Er.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<n.length;)n[i].fn===t?n.splice(i,1):++i;return this};Er.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<t.length;)t[i].fn.apply(t[i++].ctx,n)}return this}});var Ls=S((Kp,Cs)=>{"use strict";Cs.exports=Es(Es);function Es(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,Ss),r.writeFloatBE=e.bind(null,Ts);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,As),r.readFloatBE=t.bind(null,Bs)}(),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 h=Math.floor(Math.log(s)/Math.LN2);h===1024&&(h=1023),l=s*Math.pow(2,-h),n(l*4503599627370496>>>0,a,c+i),n((u<<31|h+1023<<20|l*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,Ss,0,4),r.writeDoubleBE=e.bind(null,Ts,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,h=u>>>20&2047,d=4294967296*(u&1048575)+c;return h===2047?d?NaN:l*(1/0):h===0?l*5e-324*d:l*Math.pow(2,h-1075)*(d+4503599627370496)}r.readDoubleLE=t.bind(null,As,0,4),r.readDoubleBE=t.bind(null,Bs,4,0)}(),r}function Ss(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 Ts(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 As(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function Bs(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Ps=S((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 Ns=S(Is=>{"use strict";var Xn=Is;Xn.length=function(e){for(var t=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,t+=4):t+=3;return t};Xn.read=function(e,t,n){var i=n-t;if(i<1)return"";for(var o=null,s=[],a=0,c;t<n;)c=e[t++],c<128?s[a++]=c:c>191&&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))};Xn.write=function(e,t,n){for(var i=n,o,s,a=0;a<e.length;++a)o=e.charCodeAt(a),o<128?t[n++]=o:o<2048?(t[n++]=o>>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 Ms=S((Jp,Ds)=>{"use strict";Ds.exports=Pf;function Pf(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 Os=S((Zp,Fs)=>{"use strict";Fs.exports=R;var Ht=Je();function R(r,e){this.lo=r>>>0,this.hi=e>>>0}var Xe=R.zero=new R(0,0);Xe.toNumber=function(){return 0};Xe.zzEncode=Xe.zzDecode=function(){return this};Xe.length=function(){return 1};var If=R.zeroHash="\0\0\0\0\0\0\0\0";R.fromNumber=function(e){if(e===0)return Xe;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 R(n,i)};R.from=function(e){if(typeof e=="number")return R.fromNumber(e);if(Ht.isString(e))if(Ht.Long)e=Ht.Long.fromString(e);else return R.fromNumber(parseInt(e,10));return e.low||e.high?new R(e.low>>>0,e.high>>>0):Xe};R.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};R.prototype.toLong=function(e){return Ht.Long?new Ht.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Me=String.prototype.charCodeAt;R.fromHash=function(e){return e===If?Xe:new R((Me.call(e,0)|Me.call(e,1)<<8|Me.call(e,2)<<16|Me.call(e,3)<<24)>>>0,(Me.call(e,4)|Me.call(e,5)<<8|Me.call(e,6)<<16|Me.call(e,7)<<24)>>>0)};R.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)};R.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};R.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};R.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 Je=S(Jn=>{"use strict";var _=Jn;_.asPromise=gs();_.base64=vs();_.EventEmitter=ks();_.float=Ls();_.inquire=Ps();_.utf8=Ns();_.pool=Ms();_.LongBits=Os();_.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);_.global=_.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Jn;_.emptyArray=Object.freeze?Object.freeze([]):[];_.emptyObject=Object.freeze?Object.freeze({}):{};_.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};_.isString=function(e){return typeof e=="string"||e instanceof String};_.isObject=function(e){return e&&typeof e=="object"};_.isset=_.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};_.Buffer=function(){try{var r=_.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();_._Buffer_from=null;_._Buffer_allocUnsafe=null;_.newBuffer=function(e){return typeof e=="number"?_.Buffer?_._Buffer_allocUnsafe(e):new _.Array(e):_.Buffer?_._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};_.Array=typeof Uint8Array<"u"?Uint8Array:Array;_.Long=_.global.dcodeIO&&_.global.dcodeIO.Long||_.global.Long||_.inquire("long");_.key2Re=/^true|false|0|1$/;_.key32Re=/^-?(?:0|[1-9][0-9]*)$/;_.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;_.longToHash=function(e){return e?_.LongBits.from(e).toHash():_.LongBits.zeroHash};_.longFromHash=function(e,t){var n=_.LongBits.fromHash(e);return _.Long?_.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Us(r,e,t){for(var n=Object.keys(e),i=0;i<n.length;++i)(r[n[i]]===void 0||!t)&&(r[n[i]]=e[n[i]]);return r}_.merge=Us;_.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Rs(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&Us(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}_.newError=Rs;_.ProtocolError=Rs("ProtocolError");_.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var i=Object.keys(this),o=i.length-1;o>-1;--o)if(t[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};_.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};_.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};_._configure=function(){var r=_.Buffer;if(!r){_._Buffer_from=_._Buffer_allocUnsafe=null;return}_._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},_._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var ei=S((em,qs)=>{"use strict";qs.exports=M;var we=Je(),Yn,Ws=we.LongBits,Nf=we.utf8;function de(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function M(r){this.buf=r,this.pos=0,this.len=r.length}var zs=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new M(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new M(e);throw Error("illegal buffer")},Hs=function(){return we.Buffer?function(t){return(M.create=function(i){return we.Buffer.isBuffer(i)?new Yn(i):zs(i)})(t)}:zs};M.create=Hs();M.prototype._slice=we.Array.prototype.subarray||we.Array.prototype.slice;M.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,de(this,10);return e}}();M.prototype.int32=function(){return this.uint32()|0};M.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Zn(){var r=new Ws(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>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 de(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw de(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}M.prototype.bool=function(){return this.uint32()!==0};function Sr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}M.prototype.fixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)};M.prototype.sfixed32=function(){if(this.pos+4>this.len)throw de(this,4);return Sr(this.buf,this.pos+=4)|0};function $s(){if(this.pos+8>this.len)throw de(this,8);return new Ws(Sr(this.buf,this.pos+=4),Sr(this.buf,this.pos+=4))}M.prototype.float=function(){if(this.pos+4>this.len)throw de(this,4);var e=we.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};M.prototype.double=function(){if(this.pos+8>this.len)throw de(this,4);var e=we.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};M.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw de(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)};M.prototype.string=function(){var e=this.bytes();return Nf.read(e,0,e.length)};M.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw de(this,e);this.pos+=e}else do if(this.pos>=this.len)throw de(this);while(this.buf[this.pos++]&128);return this};M.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};M._configure=function(r){Yn=r,M.create=Hs(),Yn._configure();var e=we.Long?"toLong":"toNumber";we.merge(M.prototype,{int64:function(){return Zn.call(this)[e](!1)},uint64:function(){return Zn.call(this)[e](!0)},sint64:function(){return Zn.call(this).zzDecode()[e](!1)},fixed64:function(){return $s.call(this)[e](!0)},sfixed64:function(){return $s.call(this)[e](!1)}})}});var Qs=S((tm,Gs)=>{"use strict";Gs.exports=Ze;var js=ei();(Ze.prototype=Object.create(js.prototype)).constructor=Ze;var Vs=Je();function Ze(r){js.call(this,r)}Ze._configure=function(){Vs.Buffer&&(Ze.prototype._slice=Vs.Buffer.prototype.slice)};Ze.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))};Ze._configure()});var ai=S((rm,Zs)=>{"use strict";Zs.exports=T;var ce=Je(),ti,Tr=ce.LongBits,Ks=ce.base64,Xs=ce.utf8;function qt(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function ni(){}function Df(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function T(){this.len=0,this.head=new qt(ni,0,0),this.tail=this.head,this.states=null}var Js=function(){return ce.Buffer?function(){return(T.create=function(){return new ti})()}:function(){return new T}};T.create=Js();T.alloc=function(e){return new ce.Array(e)};ce.Array!==Array&&(T.alloc=ce.pool(T.alloc,ce.Array.prototype.subarray));T.prototype._push=function(e,t,n){return this.tail=this.tail.next=new qt(e,t,n),this.len+=t,this};function ii(r,e,t){e[t]=r&255}function Mf(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function oi(r,e){this.len=r,this.next=void 0,this.val=e}oi.prototype=Object.create(qt.prototype);oi.prototype.fn=Mf;T.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new oi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};T.prototype.int32=function(e){return e<0?this._push(si,10,Tr.fromNumber(e)):this.uint32(e)};T.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function si(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}T.prototype.uint64=function(e){var t=Tr.from(e);return this._push(si,t.length(),t)};T.prototype.int64=T.prototype.uint64;T.prototype.sint64=function(e){var t=Tr.from(e).zzEncode();return this._push(si,t.length(),t)};T.prototype.bool=function(e){return this._push(ii,1,e?1:0)};function ri(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}T.prototype.fixed32=function(e){return this._push(ri,4,e>>>0)};T.prototype.sfixed32=T.prototype.fixed32;T.prototype.fixed64=function(e){var t=Tr.from(e);return this._push(ri,4,t.lo)._push(ri,4,t.hi)};T.prototype.sfixed64=T.prototype.fixed64;T.prototype.float=function(e){return this._push(ce.float.writeFloatLE,4,e)};T.prototype.double=function(e){return this._push(ce.float.writeDoubleLE,8,e)};var Ff=ce.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i<e.length;++i)t[n+i]=e[i]};T.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(ii,1,0);if(ce.isString(e)){var n=T.alloc(t=Ks.length(e));Ks.decode(e,n,0),e=n}return this.uint32(t)._push(Ff,t,e)};T.prototype.string=function(e){var t=Xs.length(e);return t?this.uint32(t)._push(Xs.write,t,e):this._push(ii,1,0)};T.prototype.fork=function(){return this.states=new Df(this),this.head=this.tail=new qt(ni,0,0),this.len=0,this};T.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 qt(ni,0,0),this.len=0),this};T.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};T.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};T._configure=function(r){ti=r,T.create=Js(),ti._configure()}});var ta=S((nm,ea)=>{"use strict";ea.exports=be;var Ys=ai();(be.prototype=Object.create(Ys.prototype)).constructor=be;var Fe=Je();function be(){Ys.call(this)}be._configure=function(){be.alloc=Fe._Buffer_allocUnsafe,be.writeBytesBuffer=Fe.Buffer&&Fe.Buffer.prototype instanceof Uint8Array&&Fe.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<e.length;)t[n++]=e[i++]}};be.prototype.bytes=function(e){Fe.isString(e)&&(e=Fe._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(be.writeBytesBuffer,t,e),this};function Of(r,e,t){r.length<40?Fe.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}be.prototype.string=function(e){var t=Fe.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Of,t,e),this};be._configure()});var Or=S((by,ya)=>{"use strict";function ma(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Yf(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 ma(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),ma(new i,t)}}ya.exports=Yf});var xa=S((Oy,va)=>{"use strict";va.exports=function(){return Date.now()}});var Ea=S((Uy,ka)=>{"use strict";var zr=xa(),_i=class{constructor(e,t,n){let i=this;this._started=zr(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(zr()-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=zr();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=zr(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function ch(){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<r.length;e++)r[e]=arguments[e+2]}return new _i(arguments[0],arguments[1],r)}ka.exports=ch});var Aa=S((Ry,Ta)=>{"use strict";var{AbortController:uh}=globalThis,Sa=Ea(),jt=class extends uh{constructor(e){super(),this._ms=e,this._timer=Sa(()=>this.abort(),e),Object.setPrototypeOf(this,jt.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=Sa(()=>this.abort(),this._ms)}};Ta.exports={TimeoutController:jt}});var Qr=S((kg,Ti)=>{"use strict";var Tt=typeof Reflect=="object"?Reflect:null,Na=Tt&&typeof Tt.apply=="function"?Tt.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},jr;Tt&&typeof Tt.ownKeys=="function"?jr=Tt.ownKeys:Object.getOwnPropertySymbols?jr=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:jr=function(e){return Object.getOwnPropertyNames(e)};function Eh(r){console&&console.warn&&console.warn(r)}var Ma=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}Ti.exports=L;Ti.exports.once=Bh;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var Da=10;function Gr(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return Da},set:function(r){if(typeof r!="number"||r<0||Ma(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");Da=r}});L.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};L.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Ma(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 Fa(r){return r._maxListeners===void 0?L.defaultMaxListeners:r._maxListeners}L.prototype.getMaxListeners=function(){return Fa(this)};L.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(t.length>0&&(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")Na(c,this,t);else for(var u=c.length,l=$a(c,u),n=0;n<u;++n)Na(l[n],this,t);return!0};function Oa(r,e,t,n){var i,o,s;if(Gr(t),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),o=r._events),s=o[e]),s===void 0)s=o[e]=t,++r._eventsCount;else if(typeof s=="function"?s=o[e]=n?[t,s]:[s,t]:n?s.unshift(t):s.push(t),i=Fa(r),i>0&&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,Eh(a)}return r}L.prototype.addListener=function(e,t){return Oa(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return Oa(this,e,t,!0)};function Sh(){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 Ua(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=Sh.bind(n);return i.listener=t,n.wrapFn=i,i}L.prototype.once=function(e,t){return Gr(t),this.on(e,Ua(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Gr(t),this.prependListener(e,Ua(this,e,t)),this};L.prototype.removeListener=function(e,t){var n,i,o,s,a;if(Gr(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():Th(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};L.prototype.off=L.prototype.removeListener;L.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<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function Ra(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?Ah(i):$a(i,i.length)}L.prototype.listeners=function(e){return Ra(this,e,!0)};L.prototype.rawListeners=function(e){return Ra(this,e,!1)};L.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):za.call(r,e)};L.prototype.listenerCount=za;function za(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}L.prototype.eventNames=function(){return this._eventsCount>0?jr(this._events):[]};function $a(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function Th(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Ah(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Bh(r,e){return new Promise(function(t,n){function i(s){r.removeListener(e,o),n(s)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}Wa(r,e,o,{once:!0}),e!=="error"&&Ch(r,i,{once:!0})})}function Ch(r,e,t){typeof r.on=="function"&&Wa(r,"error",e,t)}function Wa(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(o){n.once&&r.removeEventListener(e,i),t(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var Ja=S((Ka,Xa)=>{"use strict";var qh=Math.exp;Ka=Xa.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-qh(-(u-l)/e)}return a.push=function(l,h){if(s){let d=c(l,s),v=h-t,y=d*v;t=d*h+(1-d)*t,n=(1-d)*(n+v*y),i=Math.sqrt(n),o=t+d*v}else t=h;s=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return o},a}});var rc=S((ew,Ui)=>{function tc(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}Ui.exports=tc;Ui.exports.anySignal=tc});var sc=S((yw,Ri)=>{"use strict";var Zh=Object.prototype.hasOwnProperty,q="~";function Zt(){}Object.create&&(Zt.prototype=Object.create(null),new Zt().__proto__||(q=!1));function Yh(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function oc(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Yh(t,n||r,i),s=q?q+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 en(r,e){--r._eventsCount===0?r._events=new Zt:delete r._events[e]}function H(){this._events=new Zt,this._eventsCount=0}H.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Zh.call(t,n)&&e.push(q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};H.prototype.listeners=function(e){var t=q?q+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<o;i++)s[i]=n[i].fn;return s};H.prototype.listenerCount=function(e){var t=q?q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};H.prototype.emit=function(e,t,n,i,o,s){var a=q?q+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d=c.length,v;for(h=0;h<d;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(v=1,l=new Array(u-1);v<u;v++)l[v-1]=arguments[v];c[h].fn.apply(c[h].context,l)}}return!0};H.prototype.on=function(e,t,n){return oc(this,e,t,n,!1)};H.prototype.once=function(e,t,n){return oc(this,e,t,n,!0)};H.prototype.removeListener=function(e,t,n,i){var o=q?q+e:e;if(!this._events[o])return this;if(!t)return en(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&en(this,o);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:en(this,o)}return this};H.prototype.removeAllListeners=function(e){var t;return e?(t=q?q+e:e,this._events[t]&&en(this,t)):(this._events=new Zt,this._eventsCount=0),this};H.prototype.off=H.prototype.removeListener;H.prototype.addListener=H.prototype.on;H.prefixed=q;H.EventEmitter=H;typeof Ri<"u"&&(Ri.exports=H)});var ep={};V(ep,{createHelia:()=>Yd});var Dn={};V(Dn,{identity:()=>Nn});var rp=new Uint8Array(0);var ko=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},ke=r=>{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 Eo=r=>new TextEncoder().encode(r),So=r=>new TextDecoder().decode(r);var tl=Co,Ao=128,rl=127,nl=~rl,il=Math.pow(2,31);function Co(r,e,t){e=e||[],t=t||0;for(var n=t;r>=il;)e[t++]=r&255|Ao,r/=128;for(;r&nl;)e[t++]=r&255|Ao,r>>>=7;return e[t]=r|0,Co.bytes=t-n+1,e}var ol=In,sl=128,Bo=127;function In(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw In.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Bo)<<i:(s&Bo)*Math.pow(2,i),i+=7}while(s>=sl);return In.bytes=o-n,t}var al=Math.pow(2,7),cl=Math.pow(2,14),ul=Math.pow(2,21),ll=Math.pow(2,28),fl=Math.pow(2,35),hl=Math.pow(2,42),dl=Math.pow(2,49),pl=Math.pow(2,56),ml=Math.pow(2,63),yl=function(r){return r<al?1:r<cl?2:r<ul?3:r<ll?4:r<fl?5:r<hl?6:r<dl?7:r<pl?8:r<ml?9:10},gl={encode:tl,decode:ol,encodingLength:yl},wl=gl,Ut=wl;var Rt=(r,e=0)=>[Ut.decode(r,e),Ut.decode.bytes],lt=(r,e,t=0)=>(Ut.encode(r,e,t),e),ft=r=>Ut.encodingLength(r);var Ve=(r,e)=>{let t=e.byteLength,n=ft(r),i=n+ft(t),o=new Uint8Array(i+t);return lt(r,o,0),lt(t,o,n),o.set(e,i),new ht(r,t,e,o)},br=r=>{let e=ke(r),[t,n]=Rt(e),[i,o]=Rt(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ht(t,i,s,e)},Lo=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ko(r.bytes,t.bytes)}},ht=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var Po=0,bl="identity",Io=ke,_l=r=>Ve(Po,Io(r)),Nn={code:Po,name:bl,encode:Io,digest:_l};var Un={};V(Un,{sha256:()=>je,sha512:()=>On});var Fn=({name:r,code:e,encode:t})=>new Mn(r,e,t),Mn=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?Ve(this.code,t):t.then(n=>Ve(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Do=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),je=Fn({name:"sha2-256",code:18,encode:Do("SHA-256")}),On=Fn({name:"sha2-512",code:19,encode:Do("SHA-512")});var Hn={};V(Hn,{base58btc:()=>E,base58flickr:()=>Tl});function vl(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,k=0,I=0,O=y.length;I!==O&&y[I]===0;)I++,g++;for(var ne=(O-I)*l+1>>>0,$=new Uint8Array(ne);I!==O;){for(var fe=y[I],ie=0,Q=ne-1;(fe!==0||ie<k)&&Q!==-1;Q--,ie++)fe+=256*$[Q]>>>0,$[Q]=fe%a>>>0,fe=fe/a>>>0;if(fe!==0)throw new Error("Non-zero carry");k=ie,I++}for(var oe=ne-k;oe!==ne&&$[oe]===0;)oe++;for(var ut=c.repeat(g);oe<ne;++oe)ut+=r.charAt($[oe]);return ut}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var k=0,I=0;y[g]===c;)k++,g++;for(var O=(y.length-g)*u+1>>>0,ne=new Uint8Array(O);y[g];){var $=t[y.charCodeAt(g)];if($===255)return;for(var fe=0,ie=O-1;($!==0||fe<I)&&ie!==-1;ie--,fe++)$+=a*ne[ie]>>>0,ne[ie]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=fe,g++}if(y[g]!==" "){for(var Q=O-I;Q!==O&&ne[Q]===0;)Q++;for(var oe=new Uint8Array(k+(O-Q)),ut=k;Q!==O;)oe[ut++]=ne[Q++];return oe}}}function v(y){var g=d(y);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:v}}var xl=vl,kl=xl,Mo=kl;var Rn=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")}},zn=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 Fo(this,e)}},$n=class{constructor(e){this.decoders=e}or(e){return Fo(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`)}},Fo=(r,e)=>new $n({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Wn=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Rn(e,t,n),this.decoder=new zn(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pt=({name:r,prefix:e,encode:t,decode:n})=>new Wn(r,e,t,n),Ne=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=Mo(t,e);return pt({prefix:r,name:e,encode:n,decode:o=>ke(i(o))})},El=(r,e,t,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},Sl=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s&&(o+=e[i&a<<t-s]),n)for(;o.length*t&7;)o+="=";return o},D=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>pt({prefix:e,name:r,encode(i){return Sl(i,n,t)},decode(i){return El(i,n,t,r)}});var E=Ne({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tl=Ne({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qn={};V(qn,{base32:()=>j,base32hex:()=>Ll,base32hexpad:()=>Il,base32hexpadupper:()=>Nl,base32hexupper:()=>Pl,base32pad:()=>Bl,base32padupper:()=>Cl,base32upper:()=>Al,base32z:()=>Dl});var j=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Al=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bl=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cl=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ll=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pl=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Il=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nl=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Dl=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Oo=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return Fl(t,Vn(r),e||E.encoder);default:return Ol(t,Vn(r),e||j.encoder)}};var Uo=new WeakMap,Vn=r=>{let e=Uo.get(r);if(e==null){let t=new Map;return Uo.set(r,t),t}return e},x=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!==zt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ul)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return x.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=Ve(e,t);return x.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 x.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&Lo(e.multihash,n.multihash)}toString(e){return Oo(this,e)}toJSON(){return{"/":Oo(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 x)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new x(n,i,o,s||Ro(n,i,o.bytes))}else if(t[Rl]===!0){let{version:n,multihash:i,code:o}=t,s=br(i);return x.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!==zt)throw new Error(`Version 0 CID must use dag-pb (code: ${zt}) block encoding`);return new x(e,t,n,n.bytes)}case 1:{let i=Ro(e,t,n.bytes);return new x(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return x.create(0,zt,e)}static createV1(e,t){return x.create(1,e,t)}static decode(e){let[t,n]=x.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=x.inspectBytes(e),n=t.size-t.multihashSize,i=ke(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 ht(t.multihashCode,t.digestSize,o,i);return[t.version===0?x.createV0(s):x.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=Rt(e.subarray(t));return t+=d,h},i=n(),o=zt;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]=Ml(e,t),o=x.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Vn(o).set(n,e),o}},Ml=(r,e)=>{switch(r[0]){case"Q":{let t=e||E;return[E.prefix,t.decode(`${E.prefix}${r}`)]}case E.prefix:{let t=e||E;return[E.prefix,t.decode(r)]}case j.prefix:{let t=e||j;return[j.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)]}}},Fl=(r,e,t)=>{let{prefix:n}=t;if(n!==E.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},Ol=(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},zt=112,Ul=18,Ro=(r,e,t)=>{let n=ft(r),i=n+ft(e),o=new Uint8Array(i+t.byteLength);return lt(r,o,0),lt(e,o,n),o.set(t,i),o},Rl=Symbol.for("@ipld/js-cid/CID");var sa=U(Yo(),1);var $t=U(us(),1);function df(r){let e=new Uint8Array(r.reduce((n,i)=>n+$t.default.encodingLength(i),0)),t=0;for(let n of r)e=$t.encode(n,e,t),t+=$t.default.encodingLength(n);return e}var ls=df;var se=U(ms(),1);var Kn={};V(Kn,{base64:()=>Wt,base64pad:()=>Tf,base64url:()=>Af,base64urlpad:()=>Bf});var Wt=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Tf=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Af=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bf=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});se.default.formatters.b=r=>r==null?"undefined":E.baseEncode(r);se.default.formatters.t=r=>r==null?"undefined":j.baseEncode(r);se.default.formatters.m=r=>r==null?"undefined":Wt.baseEncode(r);se.default.formatters.p=r=>r==null?"undefined":r.toString();se.default.formatters.c=r=>r==null?"undefined":r.toString();se.default.formatters.k=r=>r==null?"undefined":r.toString();function Cf(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 wt(r){let e=Cf(`${r}:trace`);return se.default.enabled(`${r}:trace`)&&se.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,se.default)(`${r}:trace`)),Object.assign((0,se.default)(r),{error:(0,se.default)(`${r}:error`),trace:e})}function Qe(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Ke=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 <key: ${this.cid.toString(E)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var De=class{constructor(e,t,n,i,o){this.entry=new Ke(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(E)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var ae=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),wt(t.join(":"))};var xr=(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&&!Qe(n,i)||n instanceof De&&i instanceof De&&!n.equals(i))return!1}return!0};var ci=U(ei(),1),ra=U(Qs(),1),na=U(Je(),1),ui=U(ai(),1),ia=U(ta(),1);function Uf(){na.default._configure(),ci.default._configure(ra.default),ui.default._configure(ia.default)}Uf();var oa=["uint64","int64","sint64","fixed64","sfixed64"];function Rf(r){for(let e of oa){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function li(r){return Rf(new ci.default(r))}function zf(r){for(let e of oa){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function fi(){return zf(ui.default.create())}function Ye(r,e){let t=li(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function et(r,e){let t=fi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var _t;(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"})(_t||(_t={}));function Ar(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Br(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 Ar("enum",_t.VARINT,t,n)}function tt(r,e){return Ar("message",_t.LENGTH_DELIMITED,r,e)}var G;(function(r){let e;(function(a){let c;(function(d){d.Block="Block",d.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(d){d[d.Block=0]="Block",d[d.Have=1]="Have"})(u||(u={})),function(d){d.codec=()=>Br(u)}(c=a.WantType||(a.WantType={}));let l;(function(d){let v;d.codec=()=>(v==null&&(v=tt((y,g,k={})=>{k.lengthDelimited!==!1&&g.fork(),y.block!=null&&y.block.byteLength>0&&(g.uint32(10),g.bytes(y.block)),y.priority!=null&&y.priority!==0&&(g.uint32(16),g.int32(y.priority)),y.cancel!=null&&y.cancel!==!1&&(g.uint32(24),g.bool(y.cancel)),y.wantType!=null&&u[y.wantType]!==0&&(g.uint32(32),r.Wantlist.WantType.codec().encode(y.wantType,g)),y.sendDontHave!=null&&y.sendDontHave!==!1&&(g.uint32(40),g.bool(y.sendDontHave)),k.lengthDelimited!==!1&&g.ldelim()},(y,g)=>{let k={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},I=g==null?y.len:y.pos+g;for(;y.pos<I;){let O=y.uint32();switch(O>>>3){case 1:k.block=y.bytes();break;case 2:k.priority=y.int32();break;case 3:k.cancel=y.bool();break;case 4:k.wantType=r.Wantlist.WantType.codec().decode(y);break;case 5:k.sendDontHave=y.bool();break;default:y.skipType(O&7);break}}return k})),v),d.encode=y=>et(y,d.codec()),d.decode=y=>Ye(y,d.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=tt((d,v,y={})=>{if(y.lengthDelimited!==!1&&v.fork(),d.entries!=null)for(let g of d.entries)v.uint32(10),r.Wantlist.Entry.codec().encode(g,v);d.full!=null&&d.full!==!1&&(v.uint32(16),v.bool(d.full)),y.lengthDelimited!==!1&&v.ldelim()},(d,v)=>{let y={entries:[],full:!1},g=v==null?d.len:d.pos+v;for(;d.pos<g;){let k=d.uint32();switch(k>>>3){case 1:y.entries.push(r.Wantlist.Entry.codec().decode(d,d.uint32()));break;case 2:y.full=d.bool();break;default:d.skipType(k&7);break}}return y})),h),a.encode=d=>et(d,a.codec()),a.decode=d=>Ye(d,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=tt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.prefix=u.bytes();break;case 2:h.data=u.bytes();break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>et(u,a.codec()),a.decode=u=>Ye(u,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>Br(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=tt((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={cid:new Uint8Array(0),type:n.Have},d=l==null?u.len:u.pos+l;for(;u.pos<d;){let v=u.uint32();switch(v>>>3){case 1:h.cid=u.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(v&7);break}}return h})),c),a.encode=u=>et(u,a.codec()),a.decode=u=>Ye(u,a.codec())})(o=r.BlockPresence||(r.BlockPresence={}));let s;r.codec=()=>(s==null&&(s=tt((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return u})),s),r.encode=a=>et(a,r.codec()),r.decode=a=>Ye(a,r.codec())})(G||(G={}));var Cr=class extends Error{constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var $f,B=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=B.WantType.Block);let s=e.toString(E),a=this.wantlist.get(s);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),o===!0&&(a.sendDontHave=!!o),n===B.WantType.Block&&a.wantType===B.WantType.Have&&(a.wantType=n)):this.wantlist.set(s,new De(e,t,n,i,o))}addBlock(e,t){let n=e.toString(E);this.blocks.set(n,t)}addHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(E);this.blockPresences.has(t)||this.blockPresences.set(t,B.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(E);this.wantlist.delete(t),this.addEntry(e,0,B.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return G.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:G.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}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},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=x.parse(t),o=i.version,s=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=ls([o,s,a,c]);e.payload.push({prefix:u,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:x.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),G.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!xr(this.wantlist,e.wantlist)||!xr(this.blocks,e.blocks)||!xr(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}};$f=B;B.Entry=De;B.WantType={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have};B.BlockPresenceType={Have:G.BlockPresenceType.Have,DontHave:G.BlockPresenceType.DontHave};B.deserialize=async(r,e)=>{let t=G.decode(r),n=t.wantlist?.full===!0,i=new B(n);return t.wantlist?.entries.forEach(o=>{if(o.block==null)return;let s=x.decode(o.block);i.addEntry(s,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),t.blockPresences.forEach(o=>{if(o.cid==null)return;let s=x.decode(o.cid);o.type===B.BlockPresenceType.Have?i.addHave(s):i.addDontHave(s)}),t.blocks.length>0?(await Promise.all(t.blocks.map(async o=>{let s=await je.digest(o),a=x.createV0(s);i.addBlock(a,o)})),i):(t.payload.length>0&&(await Promise.all(t.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let s=(0,sa.default)(o.prefix),a=s[0],c=s[1],u=s[2],l=u===je.code?je:await e?.getHasher(u);if(l==null)throw new Cr("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let h=await l.digest(o.data),d=x.create(a,c,h);i.addBlock(d,o.data)})),i.setPendingBytes(t.pendingBytes)),i)};B.blockPresenceSize=r=>r.bytes.length+1;var hi=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 Oe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new hi({name:e,metrics:t}):n=new Map,n}var aa={Block:G.Wantlist.WantType.Block,Have:G.Wantlist.WantType.Have},Wf=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),o=r(n);return i<o?-1:i>o?1:0}),Ee=class{constructor(e,t){this.set=t!=null?Oe({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(E),o=this.set.get(i);o!=null?(o.inc(),o.priority=t,o.wantType===aa.Have&&n===aa.Block&&(o.wantType=n)):(this.set.set(i,new Ke(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(E),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(Wf(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(E);return this.set.has(t)}get(e){let t=e.toString(E);return this.set.get(t)}};Ee.Entry=Ke;var ca=Math.pow(2,31)-1,ua=1e3,la=1;var fa=Hf;function Hf(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 h=i;return i=null,h()}},e),l)return i()};return a.cancel=o,a.flush=s,a}var Lr=class{constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=ae(e,"msgqueue"),this.sendEntries=fa(this.sendEntries.bind(this),la)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new B(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Pr=class{constructor(e,t,n,i){this.peers=Oe({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new Ee(n,i),this.network=t,this._peerId=e,this._log=ae(e,"want")}_addEntries(e,t,n,i={}){let o=e.map((s,a)=>new B.Entry(s,ca-a,B.WantType.Block,t));o.forEach(s=>{s.cancel?n===!0?this.wantlist.removeForce(s.cid.toString(E)):this.wantlist.remove(s.cid):(this._log("adding to wantlist"),this.wantlist.add(s.cid,s.priority))});for(let s of this.peers.values())s.addEntries(o,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new Lr(this._peerId,e,this.network);let n=new B(!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!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),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)})}};function rt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Se(r=0){return globalThis.Buffer?.alloc!=null?rt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function pe(r=0){return globalThis.Buffer?.allocUnsafe!=null?rt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function pi(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=pe(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return rt(t)}var da=Symbol.for("@achingbrain/uint8arraylist");function ha(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(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Ir(r){return!!r?.[da]}var _e=class{constructor(...e){Object.defineProperty(this,da,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ir(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(Ir(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=ha(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ha(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ir(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)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 pi(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:pi(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new _e;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<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(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(!Ir(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 h=0;h<o;h++)s[h]=-1;for(let h=0;h<i;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let d=u;d>=0;d--){let v=this.get(h+d);if(n[d]!==v){l=Math.max(1,d-a[v]);break}}if(l===0)return h}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=pe(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=Se(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=Se(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=Se(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=pe(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=Se(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=Se(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=Se(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=Se(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=Se(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof _e)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Qe(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new _e;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};function Nr(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 pa=4294967296,X=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 X(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 X(t,n)}toBytes(e,t=0){let n=Nr(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 X;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>pa&&(i=0,++n>pa&&(n=0))),new X(n,i)}static fromNumber(e){if(e===0)return new X;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 X(i,n)}static fromBytes(e,t=0){let n=Nr(e),i=new X,o=0;if(e.length-t>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(t)&127)<<o*7)>>>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)<<o*7)>>>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)<<o*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;o<5;++o){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<o*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var qf=Math.pow(2,7),Vf=Math.pow(2,14),jf=Math.pow(2,21),Gf=Math.pow(2,28),Qf=Math.pow(2,35),Kf=Math.pow(2,42),Xf=Math.pow(2,49),Jf=Math.pow(2,56),Zf=Math.pow(2,63),nt={encodingLength(r){return r<qf?1:r<Vf?2:r<jf?3:r<Gf?4:r<Qf?5:r<Kf?6:r<Xf?7:r<Jf?8:r<Zf?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=pe(nt.encodingLength(r))),X.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return X.fromBytes(r,e).toNumber(!0)}};function Dr(r){return r[Symbol.asyncIterator]!=null}var Mr=r=>{let e=nt.encodingLength(r),t=pe(e);return nt.encode(r,t),Mr.bytes=e,t};Mr.bytes=0;function Fr(r,e){e=e??{};let t=e.lengthEncoder??Mr;function*n(i){let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Dr(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Fr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mr;return new _e(t(r.byteLength),r)};var vt=U(Or(),1);var eh=8,th=1024*1024*4,it;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(it||(it={}));var mi=r=>{let e=nt.decode(r);return mi.bytes=nt.encodingLength(e),e};mi.bytes=0;function Vt(r,e){let t=new _e,n=it.LENGTH,i=-1,o=e?.lengthDecoder??mi,s=e?.maxLengthLength??eh,a=e?.maxDataLength??th;function*c(){for(;t.byteLength>0;){if(n===it.LENGTH)try{if(i=o(t),i<0)throw(0,vt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,vt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=it.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>s)throw(0,vt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===it.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=it.LENGTH}}}return Dr(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,vt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,vt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Vt.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 Vt(n,{...e??{},onLength:o=>{t=o}})};var Ur=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}},xt=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ur(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Ur(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?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function kt(r={}){return nh(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 nh(r,e){e=e??{};let t=e.onEnd,n=new xt,i,o,s,a=async()=>n.isEmpty()?s?{done:!0}:await new Promise((g,k)=>{o=I=>{o=null,n.push(I);try{g(r(n))}catch(O){k(O)}return i}}):r(n),c=g=>o!=null?o(g):(n.push(g),i),u=g=>(n=new xt,o!=null?o({error:g}):(n.push({error:g}),i)),l=g=>{if(s)return i;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:g})},h=g=>s?i:(s=!0,g!=null?u(g):c({done:!0})),d=()=>(n=new xt,h(),{done:!0}),v=g=>(h(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:d,throw:v,push:l,end:h,get readableLength(){return n.size}},t==null)return i;let y=i;return i={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return y.end(g),t!=null&&(t(g),t=void 0),i},get readableLength(){return y.readableLength}},i}function ih(r){return r[Symbol.asyncIterator]!=null}function oh(...r){let e=[];for(let t of r)ih(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=kt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Rr=oh;function gi(r,...e){if(r==null)throw new Error("Empty pipeline");if(yi(r)){let n=r;r=()=>n.source}else if(wa(r)||ga(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&yi(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)yi(t[n])&&(t[n]=ah(t[n]));return sh(...t)}var sh=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ga=r=>r?.[Symbol.asyncIterator]!=null,wa=r=>r?.[Symbol.iterator]!=null,yi=r=>r==null?!1:r.sink!=null&&r.source!=null,ah=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=kt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,o=r.source;if(ga(o))i=async function*(){yield*o,n.end()};else if(wa(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rr(n,i())}return r.source};var wi=Symbol.for("@libp2p/topology");var ba=()=>{},bi=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??ba,this.onDisconnect=e.onDisconnect??ba}get[Symbol.toStringTag](){return wi.toString()}get[wi](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function _a(r){return new bi(r)}var La=U(Aa(),1);var Gt=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ba(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 Ca(r,e,t){let n=t??{},i=Ba(r);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:h}=n;throw new Gt(l,h)}let u=new Promise((l,h)=>{s=()=>{let{abortMessage:d,abortCode:v}=n;h(new Gt(d,v))}});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 h=i.return();h instanceof Promise&&h.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}var C=class extends Event{constructor(e,t){super(e),this.detail=t}};function lh(r){return r[Symbol.asyncIterator]!=null}function fh(r,e){return lh(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Et=fh;function hh(r){return r[Symbol.asyncIterator]!=null}function dh(r){if(hh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ue=dh;function ph(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}}}var St=ph;function mh(r){return r[Symbol.asyncIterator]!=null}function yh(r,e){if(mh(r))return async function*(){for await(let a of r)yield e(a)}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of t)yield e(a)}();let s=e;return function*(){yield o;for(let a of t)yield s(a)}()}var vi=yh;var xi="/ipfs/bitswap/1.0.0",ki="/ipfs/bitswap/1.1.0",Ei="/ipfs/bitswap/1.2.0",wh=32,bh=128,_h=3e4,$r=class{constructor(e,t,n,i={}){this._log=ae(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[xi],i.b100Only!==!0&&(this._protocols.unshift(ki),this._protocols.unshift(Ei)),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??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??wh,this._maxOutboundStreams=i.maxOutboundStreams??bh,this._incomingStreamTimeout=i.incomingStreamTimeout??_h}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=_a({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(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new La.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await gi(Ca(t.source,i.signal),o=>Vt(o),async o=>{for await(let s of o){try{let a=await B.deserialize(s.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(o=>{this._log(o),t.abort(o)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new C("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Ue(Et(vi(this.findProviders(e,t),async n=>await this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new C("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new C("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new C("bitswap:network:dial",e)),await this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[Ei,ki,xi]);try{let o;switch(i.stat.protocol){case xi:o=t.serializeToBitswap100();break;case ki:case Ei:o=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await gi([o],s=>Fr(s),i)}catch(o){n.onProgress?.(new C("bitswap:network:send-wantlist:error",{peer:e,error:o})),this._log(o)}finally{i.close()}}};var Wr=class{constructor(e){this.partner=e,this.wantlist=new Ee,this.exchangeCount=0,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 Qt=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<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+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=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var vh={hasNewInfo(){return!1},merge(){}},Hr=class{constructor(e=vh){this._taskMerger=e,this._byPeer=new Qt([],qr.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new qr(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let o=t.peerId;return t.isIdle()?this._byPeer.delete(o.toString()):this._byPeer.update(0),{peerId:o,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let o of t)n.taskDone(o);this._byPeer.update(i)}},qr=class{constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Si,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>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;o<i.length&&t<e;o++){let s=i[o];n.push(s),t+=s.size,this._pending.delete(s.topic),this._activeTotalSize+=s.size,this._active.add(s)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Si=class{constructor(){this._tasks=new Qt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+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==null)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 Pa={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 Ia=B.WantType,xh=16*1024,kh=1024,Vr=class{constructor(e,t,n,i,o,s={}){this._log=ae(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(s),this.ledgerMap=Oe({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new Hr(Pa)}_processOpts(e){return{maxSizeReplaceHasWithBlock:kh,targetMessageSize:xh,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}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 B(!1);i.setPendingBytes(n);let o=[],s=new Map;for(let c of t){let u=x.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=x.parse(c),h=a.get(c);h!=null?i.addBlock(l,h):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e!=null&&this.messageSent(e,x.parse(c),u)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let o=t.wantlistContains(n);if(o==null)continue;let s=i.length,a=this._sendAsBlock(o.wantType,s),c=s;a||(c=B.blockPresenceSize(o.cid)),this._requestQueue.pushTasks(t.partner,[{topic:o.cid.toString(E),priority:o.priority,size:c,data:{blockSize:s,isWantBlock:a,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 Ee),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(E),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(E),a=n.get(s);if(a==null)o.sendDontHave&&i.push({topic:s,priority:o.priority,size:B.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===Ia.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),u=a;c||(u=B.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===Ia.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(E),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!=null)return n;let i=new Wr(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var Qa=U(Qr(),1);var Ai={};V(Ai,{identity:()=>Lh});var Lh=pt({prefix:"\0",name:"identity",encode:r=>So(r),decode:r=>Eo(r)});var Bi={};V(Bi,{base2:()=>Ph});var Ph=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ci={};V(Ci,{base8:()=>Ih});var Ih=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Li={};V(Li,{base10:()=>Nh});var Nh=Ne({prefix:"9",name:"base10",alphabet:"0123456789"});var Pi={};V(Pi,{base16:()=>Dh,base16upper:()=>Mh});var Dh=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mh=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ii={};V(Ii,{base36:()=>Kt,base36upper:()=>Fh});var Kt=Ne({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fh=Ne({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ni={};V(Ni,{base256emoji:()=>$h});var Ha=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}"),Oh=Ha.reduce((r,e,t)=>(r[t]=e,r),[]),Uh=Ha.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Rh(r){return r.reduce((e,t)=>(e+=Oh[t],e),"")}function zh(r){let e=[];for(let t of r){let n=Uh[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var $h=pt({prefix:"\u{1F680}",name:"base256emoji",encode:Rh,decode:zh});var Kr=85;var Ng=new TextEncoder,Dg=new TextDecoder;var Mi={...Ai,...Bi,...Ci,...Li,...Pi,...qn,...Ii,...Hn,...Kn,...Ni},Rg={...Un,...Dn};function Va(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var qa=Va("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Fi=Va("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=pe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hh={utf8:qa,"utf-8":qa,hex:Mi.base16,latin1:Fi,ascii:Fi,binary:Fi,...Mi},Xr=Hh;function ot(r,e="utf8"){let t=Xr[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 ja=r=>`unwant:${ot(r.multihash.bytes,"base64")}`,Ga=r=>`block:${ot(r.multihash.bytes,"base64")}`,Jr=class extends Qa.EventEmitter{constructor(e){super(),this.setMaxListeners(ua),this._log=ae(e,"notif")}hasBlock(e,t){let n=Ga(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=Ga(e),i=ja(e);return this._log(`wantBlock:${e}`),await new Promise((o,s)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new C("bitswap:want-block:unwant",e)),s(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),t.onProgress?.(new C("bitswap:want-block:block",e)),o(u)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),s(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=ja(e);this._log(t),this.emit(t)}};var ec=U(Qr(),1);var Za=U(Qr(),1),Oi=U(Ja(),1),Xt=class extends Za.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,Oi.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&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!=null&&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=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&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==null&&(s=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=s[a];c==null&&(c=s[a]=(0,Oi.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]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var Ya={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Zr=class extends ec.EventEmitter{constructor(e,t=[],n=Ya){super();let i=Object.assign({},Ya,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 Xt(t,i),this._global.on("update",o=>this.emit("update",o)),this._peers=Oe({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=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new Xt(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!=null&&(n.stop(),this._peers.delete(t))}};var nc=U(rc(),1);function Vh(r){return r[Symbol.asyncIterator]!=null}function jh(r,e){if(Vh(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var Jt=jh;var Gh={async getHasher(){throw new Error("Not implemented")}},Qh={maxInboundStreams:32,maxOutboundStreams:128,incomingStreamTimeout:3e4,hashLoader:Gh,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Kh=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],Yr=class{constructor(e,t,n={}){this._libp2p=e,this._log=ae(this.peerId),this._options=Object.assign({},Qh,n),this.stats=new Zr(e,Kh,{enabled:this._options.statsEnabled,computeThrottleTimeout:this._options.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:this._options.statsComputeThrottleMaxQueueSize}),this.network=new $r(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Vr(this.peerId,t,this.network,this.stats,e),this.wm=new Pr(this.peerId,this.network,this.stats,e),this.notifications=new Jr(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=x.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(async({cid:i,wasWanted:o,data:s})=>{await 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",e)}_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 want(e,t={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),await 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(h=>{this._log.error(h)})),await n(c,u)}},s=new AbortController,a=t.signal!=null?(0,nc.anySignal)([t.signal,s.signal]):s.signal;try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),o(e,{...t,signal:a})])}finally{s.abort()}}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.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(Jt(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}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}};var ic=(r,e,t={})=>new Yr(r,e,t);function Xh(r){return r[Symbol.asyncIterator]!=null}function Jh(r,e){if(Xh(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=St(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let s=e;return function*(){o===!0&&(yield n);for(let a of t)s(a)&&(yield a)}()}var ve=Jh;var mc=U(sc(),1);var Yt=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},zi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ac=r=>globalThis.DOMException===void 0?new zi(r):new DOMException(r),cc=r=>{let e=r.reason===void 0?ac("This operation was aborted."):r.reason;return e instanceof Error?e:ac(e)};function $i(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(cc(c)),c.addEventListener("abort",()=>{a(cc(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 Yt(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 Wi(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 st=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)},Te,er=class{constructor(){Te.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&st(this,Te,"f")[this.size-1].priority>=t.priority){st(this,Te,"f").push(n);return}let i=Wi(st(this,Te,"f"),n,(o,s)=>s.priority-o.priority);st(this,Te,"f").splice(i,0,n)}dequeue(){let e=st(this,Te,"f").shift();return e?.run}filter(e){return st(this,Te,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return st(this,Te,"f").length}};Te=new WeakMap;var N=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},b=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)},F,rr,nr,ze,an,ir,tn,me,tr,J,rn,Z,or,Re,nn,uc,lc,dc,fc,hc,on,Hi,qi,cn,pc,sn,un=class extends Error{},Ae=class extends mc.default{constructor(e){var t,n,i,o;if(super(),F.add(this),rr.set(this,void 0),nr.set(this,void 0),ze.set(this,0),an.set(this,void 0),ir.set(this,void 0),tn.set(this,0),me.set(this,void 0),tr.set(this,void 0),J.set(this,void 0),rn.set(this,void 0),Z.set(this,0),or.set(this,void 0),Re.set(this,void 0),nn.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:er,...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})`);N(this,rr,e.carryoverConcurrencyCount,"f"),N(this,nr,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),N(this,an,e.intervalCap,"f"),N(this,ir,e.interval,"f"),N(this,J,new e.queueClass,"f"),N(this,rn,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,N(this,nn,e.throwOnTimeout===!0,"f"),N(this,Re,e.autoStart===!1,"f")}get concurrency(){return b(this,or,"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})`);N(this,or,e,"f"),b(this,F,"m",cn).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:b(this,nn,"f"),...t},new Promise((n,i)=>{b(this,J,"f").enqueue(async()=>{var o,s,a;N(this,Z,(s=b(this,Z,"f"),s++,s),"f"),N(this,ze,(a=b(this,ze,"f"),a++,a),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new un("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=$i(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,b(this,F,"m",pc).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Yt&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{b(this,F,"m",dc).call(this)}},t),this.emit("add"),b(this,F,"m",on).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return b(this,Re,"f")?(N(this,Re,!1,"f"),b(this,F,"m",cn).call(this),this):this}pause(){N(this,Re,!0,"f")}clear(){N(this,J,new(b(this,rn,"f")),"f")}async onEmpty(){b(this,J,"f").size!==0&&await b(this,F,"m",sn).call(this,"empty")}async onSizeLessThan(e){b(this,J,"f").size<e||await b(this,F,"m",sn).call(this,"next",()=>b(this,J,"f").size<e)}async onIdle(){b(this,Z,"f")===0&&b(this,J,"f").size===0||await b(this,F,"m",sn).call(this,"idle")}get size(){return b(this,J,"f").size}sizeBy(e){return b(this,J,"f").filter(e).length}get pending(){return b(this,Z,"f")}get isPaused(){return b(this,Re,"f")}};rr=new WeakMap,nr=new WeakMap,ze=new WeakMap,an=new WeakMap,ir=new WeakMap,tn=new WeakMap,me=new WeakMap,tr=new WeakMap,J=new WeakMap,rn=new WeakMap,Z=new WeakMap,or=new WeakMap,Re=new WeakMap,nn=new WeakMap,F=new WeakSet,uc=function(){return b(this,nr,"f")||b(this,ze,"f")<b(this,an,"f")},lc=function(){return b(this,Z,"f")<b(this,or,"f")},dc=function(){var e;N(this,Z,(e=b(this,Z,"f"),e--,e),"f"),b(this,F,"m",on).call(this),this.emit("next")},fc=function(){b(this,F,"m",qi).call(this),b(this,F,"m",Hi).call(this),N(this,tr,void 0,"f")},hc=function(){let e=Date.now();if(b(this,me,"f")===void 0){let t=b(this,tn,"f")-e;if(t<0)N(this,ze,b(this,rr,"f")?b(this,Z,"f"):0,"f");else return b(this,tr,"f")===void 0&&N(this,tr,setTimeout(()=>{b(this,F,"m",fc).call(this)},t),"f"),!0}return!1},on=function(){if(b(this,J,"f").size===0)return b(this,me,"f")&&clearInterval(b(this,me,"f")),N(this,me,void 0,"f"),this.emit("empty"),b(this,Z,"f")===0&&this.emit("idle"),!1;if(!b(this,Re,"f")){let e=!b(this,F,"a",hc);if(b(this,F,"a",uc)&&b(this,F,"a",lc)){let t=b(this,J,"f").dequeue();return t?(this.emit("active"),t(),e&&b(this,F,"m",Hi).call(this),!0):!1}}return!1},Hi=function(){b(this,nr,"f")||b(this,me,"f")!==void 0||(N(this,me,setInterval(()=>{b(this,F,"m",qi).call(this)},b(this,ir,"f")),"f"),N(this,tn,Date.now()+b(this,ir,"f"),"f"))},qi=function(){b(this,ze,"f")===0&&b(this,Z,"f")===0&&b(this,me,"f")&&(clearInterval(b(this,me,"f")),N(this,me,void 0,"f")),N(this,ze,b(this,rr,"f")?b(this,Z,"f"):0,"f"),b(this,F,"m",cn).call(this)},cn=function(){for(;b(this,F,"m",on).call(this););},pc=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new un("The task was aborted."))},{once:!0})})},sn=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var Vi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},ji=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},yc=r=>globalThis.DOMException===void 0?new ji(r):new DOMException(r),gc=r=>{let e=r.reason===void 0?yc("This operation was aborted."):r.reason;return e instanceof Error?e:yc(e)};function Gi(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:h}=e;h.aborted&&u(gc(h)),h.addEventListener("abort",()=>{u(gc(h))})}let l=new Vi;s=o.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}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(h){u(h)}finally{o.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},a}var wc=(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 Qi="lock:worker:request-read",Ki="lock:worker:release-read",Xi="lock:master:grant-read",Ji="lock:worker:request-write",Zi="lock:worker:release-write",Yi="lock:master:grant-write";var $e={},At=r=>{r.addEventListener("message",e=>{At.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{At.dispatchEvent("message",r,e)})};At.addEventListener=(r,e)=>{$e[r]==null&&($e[r]=[]),$e[r].push(e)};At.removeEventListener=(r,e)=>{$e[r]!=null&&($e[r]=$e[r].filter(t=>t===e))};At.dispatchEvent=function(r,e,t){$e[r]!=null&&$e[r].forEach(n=>n(e,t))};var eo=At;var bc=(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 h={type:l.data.type,name:l.data.name,identifier:l.data.identifier};h.type===n&&h.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},_c=(r,e,t,n)=>async()=>{let i=wc();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)})},ed={singleProcess:!1},vc=r=>{if(r=Object.assign({},ed,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return eo.addEventListener("message",bc(t,"requestReadLock",Qi,Ki,Xi)),eo.addEventListener("message",bc(t,"requestWriteLock",Ji,Zi,Yi)),t}return{isWorker:!0,readLock:t=>_c(t,Qi,Xi,Ki),writeLock:t=>_c(t,Ji,Yi,Zi)}};var at={},We;async function to(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await Gi((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var td=(r,e)=>{if(We.isWorker===!0)return{readLock:We.readLock(r,e),writeLock:We.writeLock(r,e)};let t=new Ae({concurrency:1}),n;return{async readLock(){if(n!=null)return await to(n,e);n=new Ae({concurrency:e.concurrency,autoStart:!1});let i=n,o=to(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await to(t,e)}}},rd={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ro(r){let e=Object.assign({},rd,r);return We==null&&(We=vc(e),We.isWorker!==!0&&(We.addEventListener("requestReadLock",t=>{at[t.data.name]!=null&&at[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),We.addEventListener("requestWriteLock",async t=>{at[t.data.name]!=null&&at[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),at[e.name]==null&&(at[e.name]=td(e.name,e)),at[e.name]}var ln=class{constructor(e,t,n={}){this.child=e,this.bitswap=n.bitswap,this.pins=t,this.lock=ro({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.has(e)?(n.onProgress?.(new C("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new C("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new C("blocks:put:blockstore:put",e)),await this.child.put(e,t,n))}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{let i=ve(e,async({cid:s})=>{let a=await this.child.has(s);return a&&t.onProgress?.(new C("blocks:put-many:duplicate",s)),!a}),o=Jt(i,({cid:s,block:a})=>{t.onProgress?.(new C("blocks:put-many:bitswap:notify",s)),this.bitswap?.notify(s,a,t)});t.onProgress?.(new C("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{if(this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new C("blocks:get:bitswap:get",e));let i=await this.bitswap.want(e,t);return t.onProgress?.(new C("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),i}return t.onProgress?.(new C("blocks:get:blockstore:get",e)),await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{t.onProgress?.(new C("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Jt(e,async i=>{if(this.bitswap?.isStarted()===!0&&!await this.child.has(i)){t.onProgress?.(new C("blocks:get-many:bitswap:get",i));let o=await this.bitswap.want(i,t);t.onProgress?.(new C("blocks:get-many:blockstore:put",i)),await this.child.put(i,o,t)}}))}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");t.onProgress?.(new C("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;t.onProgress?.(new C("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new Error("CID was pinned");yield o}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{e.onProgress?.(new C("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}finally{t()}}};var xc=(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),"");function fn(r,e="utf8"){let t=Xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rt(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var Be="/",kc=new TextEncoder().encode(Be),hn=kc[0],P=class{constructor(e,t){if(typeof e=="string")this._buf=fn(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==hn)throw new Error("Invalid key")}toString(e="utf8"){return ot(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new P(e.join(Be))}static random(){return new P(xc().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new P(e):typeof e.uint8Array=="function"?new P(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=kc),this._buf[0]!==hn){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hn,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hn;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return P.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Be).slice(1)}type(){return nd(this.baseNamespace())}name(){return id(this.baseNamespace())}instance(e){return new P(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Be)||(e+=Be),e+=this.type(),new P(e)}parent(){let e=this.list();return e.length===1?new P(Be):new P(e.slice(0,-1).join(Be))}child(e){return this.toString()===Be?e:e.toString()===Be?this:new P(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return P.withNamespaces([...this.namespaces(),...od(e.map(t=>t.namespaces()))])}};function nd(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function id(r){let e=r.split(":");return e[e.length-1]}function od(r){return[].concat(...r)}var sd=["string","number","bigint","symbol"],ad=["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 Ec(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(sd.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(cd(r))return"Buffer";let t=ud(r);return t||"Object"}function cd(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function ud(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(ad.includes(e))return e}var f=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.major<e.major?-1:this.major>e.major?1:0}};f.uint=new f(0,"uint",!0);f.negint=new f(1,"negint",!0);f.bytes=new f(2,"bytes",!0);f.string=new f(3,"string",!0);f.array=new f(4,"array",!1);f.map=new f(5,"map",!1);f.tag=new f(6,"tag",!1);f.float=new f(7,"float",!0);f.false=new f(7,"false",!0);f.true=new f(7,"true",!0);f.null=new f(7,"null",!0);f.undefined=new f(7,"undefined",!0);f.break=new f(7,"break",!0);var p=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 Bt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ld=new TextDecoder,fd=new TextEncoder;function dn(r){return Bt&&globalThis.Buffer.isBuffer(r)}function sr(r){return r instanceof Uint8Array?dn(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Bc=Bt?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Tc(r,e,t):(r,e,t)=>t-e>64?ld.decode(r.subarray(e,t)):Tc(r,e,t),pn=Bt?r=>r.length>64?globalThis.Buffer.from(r):Sc(r):r=>r.length>64?fd.encode(r):Sc(r),xe=r=>Uint8Array.from(r),Ct=Bt?(r,e,t)=>dn(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Cc=Bt?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),sr(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},Lc=Bt?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Pc(r,e){if(dn(r)&&dn(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Sc(r,e=1/0){let t,n=r.length,i=null,o=[];for(let s=0;s<n;++s){if(t=r.charCodeAt(s),t>55295&&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 Tc(r,e,t){let n=[];for(;e<t;){let i=r[e],o=null,s=i>239?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 no(n)}var Ac=4096;function no(r){let e=r.length;if(e<=Ac)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ac));return t}var hd=256,ar=class{constructor(e=hd){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Lc(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Ct(n,0,this.cursor)}else t=Cc(this.chunks,this.cursor);return e&&this.reset(),t}};var w="CBOR decode error:",Lt="CBOR encode error:",cr=[];cr[23]=1;cr[24]=2;cr[25]=3;cr[26]=5;cr[27]=9;function Ce(r,e,t){if(r.length-e<t)throw new Error(`${w} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Y(r,e,t){Ce(r,e,1);let n=r[e];if(t.strict===!0&&n<z[0])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function ee(r,e,t){Ce(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<z[1])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function te(r,e,t){Ce(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<z[2])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return n}function re(r,e,t){Ce(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<z[3])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${w} integers outside of the safe integer range are not supported`)}function Ic(r,e,t,n){return new p(f.uint,Y(r,e+1,n),2)}function Nc(r,e,t,n){return new p(f.uint,ee(r,e+1,n),3)}function Dc(r,e,t,n){return new p(f.uint,te(r,e+1,n),5)}function Mc(r,e,t,n){return new p(f.uint,re(r,e+1,n),9)}function ue(r,e){return W(r,0,e.value)}function W(r,e,t){if(t<z[0]){let n=Number(t);r.push([e|n])}else if(t<z[1]){let n=Number(t);r.push([e|24,n])}else if(t<z[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<z[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<z[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(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(`${w} encountered BigInt larger than allowable range`)}}ue.encodedSize=function(e){return W.encodedSize(e.value)};W.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};ue.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Fc(r,e,t,n){return new p(f.negint,-1-Y(r,e+1,n),2)}function Oc(r,e,t,n){return new p(f.negint,-1-ee(r,e+1,n),3)}function Uc(r,e,t,n){return new p(f.negint,-1-te(r,e+1,n),5)}var io=BigInt(-1),Rc=BigInt(1);function zc(r,e,t,n){let i=re(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(f.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${w} integers outside of the safe integer range are not supported`);return new p(f.negint,io-BigInt(i),9)}function mn(r,e){let t=e.value,n=typeof t=="bigint"?t*io-Rc:t*-1-1;W(r,e.type.majorEncoded,n)}mn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*io-Rc:t*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};mn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ur(r,e,t,n){Ce(r,e,t+n);let i=Ct(r,e+t,e+t+n);return new p(f.bytes,i,t+n)}function $c(r,e,t,n){return ur(r,e,1,t)}function Wc(r,e,t,n){return ur(r,e,2,Y(r,e+1,n))}function Hc(r,e,t,n){return ur(r,e,3,ee(r,e+1,n))}function qc(r,e,t,n){return ur(r,e,5,te(r,e+1,n))}function Vc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer bytes lengths not supported`);return ur(r,e,9,i)}function yn(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===f.string?pn(r.value):r.value),r.encodedBytes}function Pt(r,e){let t=yn(e);W(r,e.type.majorEncoded,t.length),r.push(t)}Pt.encodedSize=function(e){let t=yn(e);return W.encodedSize(t.length)+t.length};Pt.compareTokens=function(e,t){return pd(yn(e),yn(t))};function pd(r,e){return r.length<e.length?-1:r.length>e.length?1:Pc(r,e)}function lr(r,e,t,n,i){let o=t+n;Ce(r,e,o);let s=new p(f.string,Bc(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=Ct(r,e+t,e+o)),s}function jc(r,e,t,n){return lr(r,e,1,t,n)}function Gc(r,e,t,n){return lr(r,e,2,Y(r,e+1,n),n)}function Qc(r,e,t,n){return lr(r,e,3,ee(r,e+1,n),n)}function Kc(r,e,t,n){return lr(r,e,5,te(r,e+1,n),n)}function Xc(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer string lengths not supported`);return lr(r,e,9,i,n)}var Jc=Pt;function It(r,e,t,n){return new p(f.array,n,t)}function Zc(r,e,t,n){return It(r,e,1,t)}function Yc(r,e,t,n){return It(r,e,2,Y(r,e+1,n))}function eu(r,e,t,n){return It(r,e,3,ee(r,e+1,n))}function tu(r,e,t,n){return It(r,e,5,te(r,e+1,n))}function ru(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer array lengths not supported`);return It(r,e,9,i)}function nu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return It(r,e,1,1/0)}function gn(r,e){W(r,f.array.majorEncoded,e.value)}gn.compareTokens=ue.compareTokens;gn.encodedSize=function(e){return W.encodedSize(e.value)};function Nt(r,e,t,n){return new p(f.map,n,t)}function iu(r,e,t,n){return Nt(r,e,1,t)}function ou(r,e,t,n){return Nt(r,e,2,Y(r,e+1,n))}function su(r,e,t,n){return Nt(r,e,3,ee(r,e+1,n))}function au(r,e,t,n){return Nt(r,e,5,te(r,e+1,n))}function cu(r,e,t,n){let i=re(r,e+1,n);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer map lengths not supported`);return Nt(r,e,9,i)}function uu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return Nt(r,e,1,1/0)}function wn(r,e){W(r,f.map.majorEncoded,e.value)}wn.compareTokens=ue.compareTokens;wn.encodedSize=function(e){return W.encodedSize(e.value)};function lu(r,e,t,n){return new p(f.tag,t,1)}function fu(r,e,t,n){return new p(f.tag,Y(r,e+1,n),2)}function hu(r,e,t,n){return new p(f.tag,ee(r,e+1,n),3)}function du(r,e,t,n){return new p(f.tag,te(r,e+1,n),5)}function pu(r,e,t,n){return new p(f.tag,re(r,e+1,n),9)}function bn(r,e){W(r,f.tag.majorEncoded,e.value)}bn.compareTokens=ue.compareTokens;bn.encodedSize=function(e){return W.encodedSize(e.value)};var _d=20,vd=21,xd=22,kd=23;function mu(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${w} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(f.null,null,1):new p(f.undefined,void 0,1)}function yu(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return new p(f.break,void 0,1)}function oo(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${w} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${w} Infinity values are not supported`)}return new p(f.float,r,e)}function gu(r,e,t,n){return oo(so(r,e+1),3,n)}function wu(r,e,t,n){return oo(ao(r,e+1),5,n)}function bu(r,e,t,n){return oo(ku(r,e+1),9,n)}function _n(r,e,t){let n=e.value;if(n===!1)r.push([f.float.majorEncoded|_d]);else if(n===!0)r.push([f.float.majorEncoded|vd]);else if(n===null)r.push([f.float.majorEncoded|xd]);else if(n===void 0)r.push([f.float.majorEncoded|kd]);else{let i,o=!1;(!t||t.float64!==!0)&&(vu(n),i=so(ye,1),n===i||Number.isNaN(n)?(ye[0]=249,r.push(ye.slice(0,3)),o=!0):(xu(n),i=ao(ye,1),n===i&&(ye[0]=250,r.push(ye.slice(0,5)),o=!0))),o||(Ed(n),i=ku(ye,1),ye[0]=251,r.push(ye.slice(0,9)))}}_n.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){vu(n);let i=so(ye,1);if(n===i||Number.isNaN(n))return 3;if(xu(n),i=ao(ye,1),n===i)return 5}return 9};var _u=new ArrayBuffer(9),le=new DataView(_u,1),ye=new Uint8Array(_u,0);function vu(r){if(r===1/0)le.setUint16(0,31744,!1);else if(r===-1/0)le.setUint16(0,64512,!1);else if(Number.isNaN(r))le.setUint16(0,32256,!1);else{le.setFloat32(0,r);let e=le.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)le.setUint16(0,31744,!1);else if(t===0)le.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?le.setUint16(0,0):i<-14?le.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):le.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function so(r,e){if(r.length-e<2)throw new Error(`${w} 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 xu(r){le.setFloat32(0,r,!1)}function ao(r,e){if(r.length-e<4)throw new Error(`${w} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Ed(r){le.setFloat64(0,r,!1)}function ku(r,e){if(r.length-e<8)throw new Error(`${w} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}_n.compareTokens=ue.compareTokens;function A(r,e,t){throw new Error(`${w} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function vn(r){return()=>{throw new Error(`${w} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=A;m[24]=Ic;m[25]=Nc;m[26]=Dc;m[27]=Mc;m[28]=A;m[29]=A;m[30]=A;m[31]=A;for(let r=32;r<=55;r++)m[r]=A;m[56]=Fc;m[57]=Oc;m[58]=Uc;m[59]=zc;m[60]=A;m[61]=A;m[62]=A;m[63]=A;for(let r=64;r<=87;r++)m[r]=$c;m[88]=Wc;m[89]=Hc;m[90]=qc;m[91]=Vc;m[92]=A;m[93]=A;m[94]=A;m[95]=vn("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=jc;m[120]=Gc;m[121]=Qc;m[122]=Kc;m[123]=Xc;m[124]=A;m[125]=A;m[126]=A;m[127]=vn("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=Zc;m[152]=Yc;m[153]=eu;m[154]=tu;m[155]=ru;m[156]=A;m[157]=A;m[158]=A;m[159]=nu;for(let r=160;r<=183;r++)m[r]=iu;m[184]=ou;m[185]=su;m[186]=au;m[187]=cu;m[188]=A;m[189]=A;m[190]=A;m[191]=uu;for(let r=192;r<=215;r++)m[r]=lu;m[216]=fu;m[217]=hu;m[218]=du;m[219]=pu;m[220]=A;m[221]=A;m[222]=A;m[223]=A;for(let r=224;r<=243;r++)m[r]=vn("simple values are not supported");m[244]=A;m[245]=A;m[246]=A;m[247]=mu;m[248]=vn("simple values are not supported");m[249]=gu;m[250]=wu;m[251]=bu;m[252]=A;m[253]=A;m[254]=A;m[255]=yu;var ge=[];for(let r=0;r<24;r++)ge[r]=new p(f.uint,r,1);for(let r=-1;r>=-24;r--)ge[31-r]=new p(f.negint,r,1);ge[64]=new p(f.bytes,new Uint8Array(0),1);ge[96]=new p(f.string,"",1);ge[128]=new p(f.array,0,1);ge[160]=new p(f.map,0,1);ge[244]=new p(f.false,!1,1);ge[245]=new p(f.true,!0,1);ge[246]=new p(f.null,null,1);function Eu(r){switch(r.type){case f.false:return xe([244]);case f.true:return xe([245]);case f.null:return xe([246]);case f.bytes:return r.value.length?void 0:xe([64]);case f.string:return r.value===""?xe([96]):void 0;case f.array:return r.value===0?xe([128]):void 0;case f.map:return r.value===0?xe([160]):void 0;case f.uint:return r.value<24?xe([Number(r.value)]):void 0;case f.negint:if(r.value>=-24)return xe([31-Number(r.value)])}}var Td={float64:!1,mapSorter:Cd,quickEncodeToken:Eu};function Ad(){let r=[];return r[f.uint.major]=ue,r[f.negint.major]=mn,r[f.bytes.major]=Pt,r[f.string.major]=Jc,r[f.array.major]=gn,r[f.map.major]=wn,r[f.tag.major]=bn,r[f.float.major]=_n,r}var Su=Ad(),co=new ar,Dt=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 Dt(t,e)}},He={null:new p(f.null,null),undefined:new p(f.undefined,void 0),true:new p(f.true,!0),false:new p(f.false,!1),emptyArray:new p(f.array,0),emptyMap:new p(f.map,0)},qe={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(f.float,r):r>=0?new p(f.uint,r):new p(f.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(f.uint,r):new p(f.negint,r)},Uint8Array(r,e,t,n){return new p(f.bytes,r)},string(r,e,t,n){return new p(f.string,r)},boolean(r,e,t,n){return r?He.true:He.false},null(r,e,t,n){return He.null},undefined(r,e,t,n){return He.undefined},ArrayBuffer(r,e,t,n){return new p(f.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(f.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[He.emptyArray,new p(f.break)]:He.emptyArray;n=Dt.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=xn(s,t,n);return t.addBreakTokens?[new p(f.array,r.length),i,new p(f.break)]:[new p(f.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?[He.emptyMap,new p(f.break)]:He.emptyMap;n=Dt.createCheck(n,r);let a=[],c=0;for(let u of o)a[c++]=[xn(u,t,n),xn(i?r.get(u):r[u],t,n)];return Bd(a,t),t.addBreakTokens?[new p(f.map,s),a,new p(f.break)]:[new p(f.map,s),a]}};qe.Map=qe.Object;qe.Buffer=qe.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))qe[`${r}Array`]=qe.DataView;function xn(r,e={},t){let n=Ec(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||qe[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=qe[n];if(!o)throw new Error(`${Lt} unsupported type: ${n}`);return o(r,n,e,t)}function Bd(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Cd(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=Su[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Tu(r,e,t,n){if(Array.isArray(e))for(let i of e)Tu(r,i,t,n);else t[e.type.major](r,e,n)}function Au(r,e,t){let n=xn(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 ar(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return sr(a.chunks[0])}}return co.reset(),Tu(co,n,e,t),co.toBytes(!0)}function kn(r,e){return e=Object.assign({},Td,e),Au(r,Su,e)}var Ld={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},uo=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=ge[e];if(t===void 0){let n=m[e];if(!n)throw new Error(`${w} 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}},fr=Symbol.for("DONE"),En=Symbol.for("BREAK");function Pd(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=hr(e,t);if(o===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed array`)}if(o===fr)throw new Error(`${w} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Id(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},o=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=hr(e,t);if(a===En){if(r.value===1/0)break;throw new Error(`${w} got unexpected break to lengthed map`)}if(a===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${w} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in i))throw new Error(`${w} found repeat map key "${a}"`);let c=hr(e,t);if(c===fr)throw new Error(`${w} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?o.set(a,c):i[a]=c}return n?o:i}function hr(r,e){if(r.done())return fr;let t=r.next();if(t.type===f.break)return En;if(t.type.terminal)return t.value;if(t.type===f.array)return Pd(t,r,e);if(t.type===f.map)return Id(t,r,e);if(t.type===f.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=hr(r,e);return e.tags[t.value](n)}throw new Error(`${w} tag not supported (${t.value})`)}throw new Error("unsupported")}function Le(r,e){if(!(r instanceof Uint8Array))throw new Error(`${w} data to decode must be a Uint8Array`);e=Object.assign({},Ld,e);let t=e.tokenizer||new uo(r,e),n=hr(t,e);if(n===fr)throw new Error(`${w} did not find any content to decode`);if(n===En)throw new Error(`${w} got unexpected break`);if(!t.done())throw new Error(`${w} too many terminals, data makes no sense`);return n}function lo(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Nd=new TextDecoder;function fo(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)<<n:(i&127)*2**n,i<128)break}return[t,e]}function Sn(r,e){let t;[t,e]=fo(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Cu(r,e){let t;return[t,e]=fo(r,e),[t&7,t>>3,e]}function Dd(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Cu(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sn(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Sn(r,n),e.Name=Nd.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=fo(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Lu(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=Cu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Sn(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Sn(r,t),n.push(Dd(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var Xb=new TextEncoder,Jb=2**32,Zb=2**31;var t0=new TextEncoder;var Pu=112;function Iu(r){let e=Lu(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=x.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 Nu=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===f.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===f.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[f.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[f.negint.major](e,t){this[f.uint.major](e,t)}[f.bytes.major](e,t){throw new Error(`${Lt} unsupported type: Uint8Array`)}[f.string.major](e,t){this.prefix(e);let n=pn(JSON.stringify(t.value));e.push(n.length>32?sr(n):n)}[f.array.major](e,t){this.prefix(e),this.inRecursive.push({type:f.array,elements:0}),e.push([91])}[f.map.major](e,t){this.prefix(e),this.inRecursive.push({type:f.map,elements:0}),e.push([123])}[f.tag.major](e,t){}[f.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===f.array)e.push([93]);else if(s.type===f.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(`${Lt} 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;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};var Mt=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}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<e.length)throw new Error(`${w} unexpected end of input at position ${this.pos}`);for(let t=0;t<e.length;t++)if(this.data[this.pos++]!==e[t])throw new Error(`${w} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=a=>{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 p(f.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(`${w} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${w} 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 p(f.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?f.uint:f.negint,s,this.pos-e):new p(s>=0?f.uint:f.negint,BigInt(o),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${w} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let o=this.pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,o));return this.pos=o+1,new p(f.string,c,s)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${w} 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(`${w} 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(`${w} unexpected unicode sequence at position ${this.pos}`);let c,u,l,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(o&31)<<6|c&63,h>127&&(s=h));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(h=(o&15)<<12|(c&63)<<6|u&63,h>2047&&(h<55296||h>57343)&&(s=h));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&&(h=(o&15)<<18|(c&63)<<12|(u&63)<<6|l&63,h>65535&&h<1114112&&(s=h))}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(`${w} 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(`${w} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new p(f.string,no(t),this.pos-e);default:if(o<32)throw new Error(`${w} invalid control character at position ${this.pos}`);o<128?(t.push(o),this.pos++):i()}}throw new Error(`${w} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new p(f.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new p(f.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(f.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(f.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(f.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(`${w} 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 p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} 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 p(f.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 p(f.break,void 0,1);if(this.ch()!==44)throw new Error(`${w} 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 p(f.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${w} 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(`${w} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function ho(r,e){return e=Object.assign({tokenizer:new Mt(r,e)},e),Le(r,e)}var Du={codec:Pu,async*walk(r){yield*Iu(r).Links.map(t=>t.Hash)}},Mu={codec:Kr,async*walk(){}},Fu=42,Ou={codec:113,async*walk(r){let e=[],t=[];t[Fu]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=x.decode(n.subarray(1));return e.push(i),i},Le(r,{tags:t}),yield*e}},po=class extends Mt{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===f.map){let t=this._next();if(t.type===f.string&&t.value==="/"){let n=this._next();if(n.type===f.string){if(this._next().type!==f.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(f.tag,42,0)}if(n.type===f.map){let i=this._next();if(i.type===f.string&&i.value==="bytes"){let o=this._next();if(o.type===f.string){for(let a=0;a<2;a++)if(this._next().type!==f.break)throw new Error("Invalid encoded Bytes form");let s=Wt.decode(`m${o.value}`);return new p(f.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Uu={codec:297,async*walk(r){let e=[],t=[];t[Fu]=n=>{let i=x.parse(n);return e.push(i),i},ho(r,{tags:t,tokenizer:new po(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var Tn=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)},Ft,mo,Ru,Od=[Mu,Du,Ou,Uu],Wu="/pin/",Hu="/pinned-block/",yo=Kt,zu=1;function $u(r){return r.version===0&&(r=r.toV1()),new P(`${Wu}${r.toString(yo)}`)}var An=class{constructor(e,t,n){Ft.add(this),this.datastore=e,this.blockstore=t,this.dagWalkers={},[...Od,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=$u(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let o=new Ae({concurrency:zu});o.add(async()=>{await Tn(this,Ft,"m",mo).call(this,e,o,c=>{c.pinnedBy.find(u=>Qe(u,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let s=lo();o.on("error",c=>{o.clear(),s.reject(c)}),await Promise.race([o.onIdle(),s.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,kn(a),t),{cid:e,...a}}async rm(e,t={}){let n=$u(e),i=await this.datastore.get(n,t),o=Le(i);await this.datastore.delete(n,t);let s=new Ae({concurrency:zu});return s.add(async()=>{await Tn(this,Ft,"m",mo).call(this,e,s,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>Qe(c,e.bytes))},{...t,depth:o.depth})}),await s.onIdle(),{cid:e,...o}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Wu+(e.cid!=null?`${e.cid.toString(Kt)}`:"")},e)){let i=x.parse(t.toString().substring(5),Kt),o=Le(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new P(`${Hu}${yo.encode(e.multihash.bytes)}`);return await this.datastore.has(n,t)}};Ft=new WeakSet,mo=async function r(e,t,n,i){if(i.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e);await Tn(this,Ft,"m",Ru).call(this,e,n,i);for await(let a of o.walk(s))t.add(async()=>{await Tn(this,Ft,"m",r).call(this,a,t,n,{...i,depth:i.depth-1})})},Ru=async function(e,t,n){let i=new P(`${Hu}${yo.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=Le(await this.datastore.get(i,n))}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(t(o),o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,kn(o),n)};var go=new P("/version"),qu=1;async function Vu(r){if(!await r.has(go)){await r.put(go,fn(`${qu}`));return}let e=await r.get(go),t=ot(e);if(parseInt(t,10)!==qu)throw new Error("Unknown datastore version, a datastore migration may be required")}var ju=U(Or(),1);function Bn(r){return r=r??new Error("Not Found"),(0,ju.default)(r,"ERR_NOT_FOUND")}var Gu="SHARDING";function Rd(r){return r[Symbol.asyncIterator]!=null}function zd(r){if(Rd(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var wo=zd;function $d(r){return r[Symbol.asyncIterator]!=null}function Wd(r,e){return $d(r)?async function*(){yield*(await wo(r)).sort(e)}():function*(){yield*wo(r).sort(e)}()}var Cn=Wd;var Pe=class{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 n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await 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 Ue(this.putMany(e,n)),e=[],await Ue(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){let i=e.prefix;n=ve(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>ve(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=ve(n,()=>i++>=o)}return e.limit!=null&&(n=Et(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=ve(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>ve(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Cn(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=ve(n,()=>o++>=i)}return e.limit!=null&&(n=Et(n,e.limit)),n}};var pr=class extends Pe{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Bn();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new P(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new P(e)}};var d1=new P(Gu);var S1=wt("datastore:core:tiered");var Ln={};V(Ln,{abortedError:()=>Jd,closeFailedError:()=>jd,deleteFailedError:()=>Kd,getFailedError:()=>Qd,hasFailedError:()=>Xd,notFoundError:()=>bo,openFailedError:()=>Vd,putFailedError:()=>Gd});var Ie=U(Or(),1);function Vd(r){return r=r??new Error("Open failed"),(0,Ie.default)(r,"ERR_OPEN_FAILED")}function jd(r){return r=r??new Error("Close failed"),(0,Ie.default)(r,"ERR_CLOSE_FAILED")}function Gd(r){return r=r??new Error("Put failed"),(0,Ie.default)(r,"ERR_PUT_FAILED")}function Qd(r){return r=r??new Error("Get failed"),(0,Ie.default)(r,"ERR_GET_FAILED")}function Kd(r){return r=r??new Error("Delete failed"),(0,Ie.default)(r,"ERR_DELETE_FAILED")}function Xd(r){return r=r??new Error("Has failed"),(0,Ie.default)(r,"ERR_HAS_FAILED")}function bo(r){return r=r??new Error("Not Found"),(0,Ie.default)(r,"ERR_NOT_FOUND")}function Jd(r){return r=r??new Error("Aborted"),(0,Ie.default)(r,"ERR_ABORTED")}var mr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var yr=class extends mr{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(j.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(j.encode(e.multihash.bytes));if(t==null)throw bo();return t}has(e){return this.data.has(j.encode(e.multihash.bytes))}async delete(e){this.data.delete(j.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:x.createV1(Kr,br(j.decode(e))),block:t}}};var G1={...Ln};var Zd=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},_o=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)},Ot,vo=wt("helia"),Pn=class{constructor(e){Ot.set(this,void 0);let t=[je,On,Nn,...e.hashers??[]],n=e.datastore??new pr,i=e.blockstore??new yr,o=e.libp2p??new Proxy({},{get(s,a){let c=()=>{};if(["start","stop"].includes(a.toString()))return c;if(a==="isProxy")return!0;throw new Error("Please configure Helia with a libp2p instance")},set(){throw new Error("Please configure Helia with a libp2p instance")}});e.libp2p!=null&&Zd(this,Ot,ic(o,i,{hashLoader:{getHasher:async s=>{let a=t.find(c=>c.code===s||c.name===s);if(a!=null)return await Promise.resolve(a);throw new Error(`Could not load hasher for code/name "${s}"`)}}}),"f"),this.pins=new An(n,i,e.dagWalkers??[]),this.libp2p=o,this.blockstore=new ln(i,this.pins,{bitswap:_o(this,Ot,"f"),holdGcLock:e.holdGcLock}),this.datastore=n}async start(){await Vu(this.datastore),await _o(this,Ot,"f")?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await _o(this,Ot,"f")?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();vo("gc start"),await Ue(i.deleteMany(async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new C("helia:gc:deleted",o))}catch(s){vo.error("Error during gc",s),e.onProgress?.(new C("helia:gc:error",s))}}()))}finally{t()}vo("gc finished")}};Ot=new WeakMap;async function Yd(r={}){let e=new Pn(r);return r.start!==!1&&await e.start(),e}return el(ep);})();
|
|
2
|
+
"use strict";var Helia=(()=>{var mD=Object.create;var eu=Object.defineProperty;var gD=Object.getOwnPropertyDescriptor;var yD=Object.getOwnPropertyNames;var wD=Object.getPrototypeOf,bD=Object.prototype.hasOwnProperty;var ED=(r,e,t)=>e in r?eu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var sh=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var je=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ae=(r,e)=>{for(var t in e)eu(r,t,{get:e[t],enumerable:!0})},J5=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yD(e))!bD.call(r,i)&&i!==t&&eu(r,i,{get:()=>e[i],enumerable:!(n=gD(e,i))||n.enumerable});return r};var F=(r,e,t)=>(t=r!=null?mD(wD(r)):{},J5(e||!r||!r.__esModule?eu(t,"default",{value:r,enumerable:!0}):t,r)),oh=r=>J5(eu({},"__esModule",{value:!0}),r);var br=(r,e,t)=>(ED(r,typeof e!="symbol"?e+"":e,t),t);var ps=T((hG,t6)=>{"use strict";function e6(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function vD(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 e6(r,t)}catch{t.message=r.message,t.stack=r.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(r)),e6(new i,t)}}t6.exports=vD});var vp=T((hY,C6)=>{var ma=1e3,ga=ma*60,ya=ga*60,yo=ya*24,eP=yo*7,tP=yo*365.25;C6.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return rP(r);if(t==="number"&&isFinite(r))return e.long?iP(r):nP(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function rP(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*tP;case"weeks":case"week":case"w":return t*eP;case"days":case"day":case"d":return t*yo;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ya;case"minutes":case"minute":case"mins":case"min":case"m":return t*ga;case"seconds":case"second":case"secs":case"sec":case"s":return t*ma;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function nP(r){var e=Math.abs(r);return e>=yo?Math.round(r/yo)+"d":e>=ya?Math.round(r/ya)+"h":e>=ga?Math.round(r/ga)+"m":e>=ma?Math.round(r/ma)+"s":r+"ms"}function iP(r){var e=Math.abs(r);return e>=yo?mh(r,e,yo,"day"):e>=ya?mh(r,e,ya,"hour"):e>=ga?mh(r,e,ga,"minute"):e>=ma?mh(r,e,ma,"second"):r+" ms"}function mh(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var k6=T((fY,P6)=>{function sP(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=i,t.enabled=o,t.humanize=vp(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let f=0;f<l.length;f++)h=(h<<5)-h+l.charCodeAt(f),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l){let h,f=null,d,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),E=b-(h||b);y.diff=E,y.prev=h,y.curr=b,h=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let R=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,I)=>{if(_==="%%")return"%";R++;let P=t.formatters[I];if(typeof P=="function"){let M=g[R];_=P.call(y,M),g.splice(R,1),R--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:g=>{f=g}}),typeof t.init=="function"&&t.init(m),m}function n(l,h){let f=t(this.namespace+(typeof h>"u"?":":h)+l);return f.log=this.log,f}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,f=(typeof l=="string"?l:"").split(/[\s,]+/),d=f.length;for(h=0;h<d;h++)f[h]&&(l=f[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let h,f;for(h=0,f=t.skips.length;h<f;h++)if(t.skips[h].test(l))return!1;for(h=0,f=t.names.length;h<f;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}P6.exports=sP});var xp=T((Qr,gh)=>{Qr.formatArgs=aP;Qr.save=cP;Qr.load=uP;Qr.useColors=oP;Qr.storage=lP();Qr.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`."))}})();Qr.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 oP(){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 aP(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gh.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)}Qr.log=console.debug||console.log||(()=>{});function cP(r){try{r?Qr.storage.setItem("debug",r):Qr.storage.removeItem("debug")}catch{}}function uP(){let r;try{r=Qr.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function lP(){try{return localStorage}catch{}}gh.exports=k6()(Qr);var{formatters:hP}=gh.exports;hP.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var B6=T((HY,O6)=>{O6.exports=L6;var N6=128,mP=127,gP=~mP,yP=Math.pow(2,31);function L6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yP;)e[t++]=r&255|N6,r/=128;for(;r&gP;)e[t++]=r&255|N6,r>>>=7;return e[t]=r|0,L6.bytes=t-n+1,e}});var F6=T(($Y,U6)=>{U6.exports=Sp;var wP=128,M6=127;function Sp(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw Sp.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&M6)<<i:(o&M6)*Math.pow(2,i),i+=7}while(o>=wP);return Sp.bytes=s-n,t}});var q6=T((GY,K6)=>{var bP=Math.pow(2,7),EP=Math.pow(2,14),vP=Math.pow(2,21),xP=Math.pow(2,28),_P=Math.pow(2,35),SP=Math.pow(2,42),AP=Math.pow(2,49),RP=Math.pow(2,56),IP=Math.pow(2,63);K6.exports=function(r){return r<bP?1:r<EP?2:r<vP?3:r<xP?4:r<_P?5:r<SP?6:r<AP?7:r<RP?8:r<IP?9:10}});var z6=T((WY,V6)=>{V6.exports={encode:B6(),decode:F6(),encodingLength:q6()}});var G6=T((YY,$6)=>{"use strict";var H6=z6();$6.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=H6.decode(r);e.push(t),r=r.slice(H6.decode.bytes)}return e}});var Q6=T((sQ,Y6)=>{Y6.exports=Ap;var W6=128,TP=127,DP=~TP,CP=Math.pow(2,31);function Ap(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Ap.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=CP;)e[t++]=r&255|W6,r/=128;for(;r&DP;)e[t++]=r&255|W6,r>>>=7;return e[t]=r|0,Ap.bytes=t-n+1,e}});var Z6=T((oQ,j6)=>{j6.exports=Rp;var PP=128,X6=127;function Rp(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a||i>49)throw Rp.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&X6)<<i:(o&X6)*Math.pow(2,i),i+=7}while(o>=PP);return Rp.bytes=s-n,t}});var eg=T((aQ,J6)=>{var kP=Math.pow(2,7),NP=Math.pow(2,14),LP=Math.pow(2,21),OP=Math.pow(2,28),BP=Math.pow(2,35),MP=Math.pow(2,42),UP=Math.pow(2,49),FP=Math.pow(2,56),KP=Math.pow(2,63);J6.exports=function(r){return r<kP?1:r<NP?2:r<LP?3:r<OP?4:r<BP?5:r<MP?6:r<UP?7:r<FP?8:r<KP?9:10}});var bo=T((cQ,tg)=>{tg.exports={encode:Q6(),decode:Z6(),encodingLength:eg()}});var Ip=T((lQ,ng)=>{"use strict";ng.exports=VP;function VP(r,e){for(var t=new Array(arguments.length-1),n=0,i=2,s=!0;i<arguments.length;)t[n++]=arguments[i++];return new Promise(function(a,c){t[n]=function(l){if(s)if(s=!1,l)c(l);else{for(var h=new Array(arguments.length-1),f=0;f<h.length;)h[f++]=arguments[f];a.apply(null,h)}};try{r.apply(e||null,t)}catch(u){s&&(s=!1,c(u))}})}});var Tp=T(og=>{"use strict";var bh=og;bh.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 wa=new Array(64),sg=new Array(123);for(qn=0;qn<64;)sg[wa[qn]=qn<26?qn+65:qn<52?qn+71:qn<62?qn-4:qn-59|43]=qn++;var qn;bh.encode=function(e,t,n){for(var i=null,s=[],o=0,a=0,c;t<n;){var u=e[t++];switch(a){case 0:s[o++]=wa[u>>2],c=(u&3)<<4,a=1;break;case 1:s[o++]=wa[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[o++]=wa[c|u>>6],s[o++]=wa[u&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=wa[c],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var ig="invalid encoding";bh.decode=function(e,t,n){for(var i=n,s=0,o,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&s>1)break;if((c=sg[c])===void 0)throw Error(ig);switch(s){case 0:o=c,s=1;break;case 1:t[n++]=o<<2|(c&48)>>4,o=c,s=2;break;case 2:t[n++]=(o&15)<<4|(c&60)>>2,o=c,s=3;break;case 3:t[n++]=(o&3)<<6|c,s=0;break}}if(s===1)throw Error(ig);return n-i};bh.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Dp=T((fQ,ag)=>{"use strict";ag.exports=Eh;function Eh(){this._listeners={}}Eh.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Eh.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<n.length;)n[i].fn===t?n.splice(i,1):++i;return this};Eh.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<t.length;)t[i].fn.apply(t[i++].ctx,n)}return this}});var Cp=T((dQ,dg)=>{"use strict";dg.exports=cg(cg);function cg(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 s(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:s,r.writeFloatBE=n?s:i;function o(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?o:a,r.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);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,s,o)}}r.writeFloatLE=e.bind(null,ug),r.writeFloatBE=e.bind(null,lg);function t(n,i,s){var o=n(i,s),a=(o>>31)*2+1,c=o>>>23&255,u=o&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,hg),r.readFloatBE=t.bind(null,fg)}(),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 s(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:s,r.writeDoubleBE=n?s:i;function o(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?o:a,r.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,c){var u=o<0?1:0;if(u&&(o=-o),o===0)n(0,a,c+i),n(1/o>0?0:2147483648,a,c+s);else if(isNaN(o))n(0,a,c+i),n(2146959360,a,c+s);else if(o>17976931348623157e292)n(0,a,c+i),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(o<22250738585072014e-324)l=o/5e-324,n(l>>>0,a,c+i),n((u<<31|l/4294967296)>>>0,a,c+s);else{var h=Math.floor(Math.log(o)/Math.LN2);h===1024&&(h=1023),l=o*Math.pow(2,-h),n(l*4503599627370496>>>0,a,c+i),n((u<<31|h+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}r.writeDoubleLE=e.bind(null,ug,0,4),r.writeDoubleBE=e.bind(null,lg,4,0);function t(n,i,s,o,a){var c=n(o,a+i),u=n(o,a+s),l=(u>>31)*2+1,h=u>>>20&2047,f=4294967296*(u&1048575)+c;return h===2047?f?NaN:l*(1/0):h===0?l*5e-324*f:l*Math.pow(2,h-1075)*(f+4503599627370496)}r.readDoubleLE=t.bind(null,hg,0,4),r.readDoubleBE=t.bind(null,fg,4,0)}(),r}function ug(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 lg(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 hg(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function fg(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Pp=T((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 Np=T(pg=>{"use strict";var kp=pg;kp.length=function(e){for(var t=0,n=0,i=0;i<e.length;++i)n=e.charCodeAt(i),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320?(++i,t+=4):t+=3;return t};kp.read=function(e,t,n){var i=n-t;if(i<1)return"";for(var s=null,o=[],a=0,c;t<n;)c=e[t++],c<128?o[a++]=c:c>191&&c<224?o[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,o[a++]=55296+(c>>10),o[a++]=56320+(c&1023)):o[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};kp.write=function(e,t,n){for(var i=n,s,o,a=0;a<e.length;++a)s=e.charCodeAt(a),s<128?t[n++]=s:s<2048?(t[n++]=s>>6|192,t[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=s&63|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=s&63|128);return n-i}});var Lp=T((mQ,mg)=>{"use strict";mg.exports=zP;function zP(r,e,t){var n=t||8192,i=n>>>1,s=null,o=n;return function(c){if(c<1||c>i)return r(c);o+c>n&&(s=r(n),o=0);var u=e.call(s,o,o+=c);return o&7&&(o=(o|7)+1),u}}});var yg=T((gQ,gg)=>{"use strict";gg.exports=Zt;var lu=vo();function Zt(r,e){this.lo=r>>>0,this.hi=e>>>0}var Eo=Zt.zero=new Zt(0,0);Eo.toNumber=function(){return 0};Eo.zzEncode=Eo.zzDecode=function(){return this};Eo.length=function(){return 1};var HP=Zt.zeroHash="\0\0\0\0\0\0\0\0";Zt.fromNumber=function(e){if(e===0)return Eo;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 Zt(n,i)};Zt.from=function(e){if(typeof e=="number")return Zt.fromNumber(e);if(lu.isString(e))if(lu.Long)e=lu.Long.fromString(e);else return Zt.fromNumber(parseInt(e,10));return e.low||e.high?new Zt(e.low>>>0,e.high>>>0):Eo};Zt.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};Zt.prototype.toLong=function(e){return lu.Long?new lu.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var ws=String.prototype.charCodeAt;Zt.fromHash=function(e){return e===HP?Eo:new Zt((ws.call(e,0)|ws.call(e,1)<<8|ws.call(e,2)<<16|ws.call(e,3)<<24)>>>0,(ws.call(e,4)|ws.call(e,5)<<8|ws.call(e,6)<<16|ws.call(e,7)<<24)>>>0)};Zt.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)};Zt.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};Zt.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};Zt.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 vo=T(Op=>{"use strict";var Z=Op;Z.asPromise=Ip();Z.base64=Tp();Z.EventEmitter=Dp();Z.float=Cp();Z.inquire=Pp();Z.utf8=Np();Z.pool=Lp();Z.LongBits=yg();Z.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);Z.global=Z.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||Op;Z.emptyArray=Object.freeze?Object.freeze([]):[];Z.emptyObject=Object.freeze?Object.freeze({}):{};Z.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Z.isString=function(e){return typeof e=="string"||e instanceof String};Z.isObject=function(e){return e&&typeof e=="object"};Z.isset=Z.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};Z.Buffer=function(){try{var r=Z.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();Z._Buffer_from=null;Z._Buffer_allocUnsafe=null;Z.newBuffer=function(e){return typeof e=="number"?Z.Buffer?Z._Buffer_allocUnsafe(e):new Z.Array(e):Z.Buffer?Z._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Z.Array=typeof Uint8Array<"u"?Uint8Array:Array;Z.Long=Z.global.dcodeIO&&Z.global.dcodeIO.Long||Z.global.Long||Z.inquire("long");Z.key2Re=/^true|false|0|1$/;Z.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Z.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Z.longToHash=function(e){return e?Z.LongBits.from(e).toHash():Z.LongBits.zeroHash};Z.longFromHash=function(e,t){var n=Z.LongBits.fromHash(e);return Z.Long?Z.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function wg(r,e,t){for(var n=Object.keys(e),i=0;i<n.length;++i)(r[n[i]]===void 0||!t)&&(r[n[i]]=e[n[i]]);return r}Z.merge=wg;Z.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function bg(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&wg(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}Z.newError=bg;Z.ProtocolError=bg("ProtocolError");Z.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var i=Object.keys(this),s=i.length-1;s>-1;--s)if(t[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};Z.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};Z.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};Z._configure=function(){var r=Z.Buffer;if(!r){Z._Buffer_from=Z._Buffer_allocUnsafe=null;return}Z._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},Z._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var Up=T((wQ,Sg)=>{"use strict";Sg.exports=Ot;var fi=vo(),Mp,xg=fi.LongBits,$P=fi.utf8;function Vn(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function Ot(r){this.buf=r,this.pos=0,this.len=r.length}var Eg=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Ot(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Ot(e);throw Error("illegal buffer")},_g=function(){return fi.Buffer?function(t){return(Ot.create=function(i){return fi.Buffer.isBuffer(i)?new Mp(i):Eg(i)})(t)}:Eg};Ot.create=_g();Ot.prototype._slice=fi.Array.prototype.subarray||fi.Array.prototype.slice;Ot.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,Vn(this,10);return e}}();Ot.prototype.int32=function(){return this.uint32()|0};Ot.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Bp(){var r=new xg(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>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 Vn(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw Vn(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}Ot.prototype.bool=function(){return this.uint32()!==0};function vh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}Ot.prototype.fixed32=function(){if(this.pos+4>this.len)throw Vn(this,4);return vh(this.buf,this.pos+=4)};Ot.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Vn(this,4);return vh(this.buf,this.pos+=4)|0};function vg(){if(this.pos+8>this.len)throw Vn(this,8);return new xg(vh(this.buf,this.pos+=4),vh(this.buf,this.pos+=4))}Ot.prototype.float=function(){if(this.pos+4>this.len)throw Vn(this,4);var e=fi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Ot.prototype.double=function(){if(this.pos+8>this.len)throw Vn(this,4);var e=fi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Ot.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Vn(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)};Ot.prototype.string=function(){var e=this.bytes();return $P.read(e,0,e.length)};Ot.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Vn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Vn(this);while(this.buf[this.pos++]&128);return this};Ot.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};Ot._configure=function(r){Mp=r,Ot.create=_g(),Mp._configure();var e=fi.Long?"toLong":"toNumber";fi.merge(Ot.prototype,{int64:function(){return Bp.call(this)[e](!1)},uint64:function(){return Bp.call(this)[e](!0)},sint64:function(){return Bp.call(this).zzDecode()[e](!1)},fixed64:function(){return vg.call(this)[e](!0)},sfixed64:function(){return vg.call(this)[e](!1)}})}});var Tg=T((bQ,Ig)=>{"use strict";Ig.exports=xo;var Rg=Up();(xo.prototype=Object.create(Rg.prototype)).constructor=xo;var Ag=vo();function xo(r){Rg.call(this,r)}xo._configure=function(){Ag.Buffer&&(xo.prototype._slice=Ag.Buffer.prototype.slice)};xo.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))};xo._configure()});var $p=T((EQ,kg)=>{"use strict";kg.exports=Be;var _n=vo(),Fp,xh=_n.LongBits,Dg=_n.base64,Cg=_n.utf8;function hu(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function qp(){}function GP(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Be(){this.len=0,this.head=new hu(qp,0,0),this.tail=this.head,this.states=null}var Pg=function(){return _n.Buffer?function(){return(Be.create=function(){return new Fp})()}:function(){return new Be}};Be.create=Pg();Be.alloc=function(e){return new _n.Array(e)};_n.Array!==Array&&(Be.alloc=_n.pool(Be.alloc,_n.Array.prototype.subarray));Be.prototype._push=function(e,t,n){return this.tail=this.tail.next=new hu(e,t,n),this.len+=t,this};function Vp(r,e,t){e[t]=r&255}function WP(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function zp(r,e){this.len=r,this.next=void 0,this.val=e}zp.prototype=Object.create(hu.prototype);zp.prototype.fn=WP;Be.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new zp((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Be.prototype.int32=function(e){return e<0?this._push(Hp,10,xh.fromNumber(e)):this.uint32(e)};Be.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Hp(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}Be.prototype.uint64=function(e){var t=xh.from(e);return this._push(Hp,t.length(),t)};Be.prototype.int64=Be.prototype.uint64;Be.prototype.sint64=function(e){var t=xh.from(e).zzEncode();return this._push(Hp,t.length(),t)};Be.prototype.bool=function(e){return this._push(Vp,1,e?1:0)};function Kp(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Be.prototype.fixed32=function(e){return this._push(Kp,4,e>>>0)};Be.prototype.sfixed32=Be.prototype.fixed32;Be.prototype.fixed64=function(e){var t=xh.from(e);return this._push(Kp,4,t.lo)._push(Kp,4,t.hi)};Be.prototype.sfixed64=Be.prototype.fixed64;Be.prototype.float=function(e){return this._push(_n.float.writeFloatLE,4,e)};Be.prototype.double=function(e){return this._push(_n.float.writeDoubleLE,8,e)};var YP=_n.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i<e.length;++i)t[n+i]=e[i]};Be.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(Vp,1,0);if(_n.isString(e)){var n=Be.alloc(t=Dg.length(e));Dg.decode(e,n,0),e=n}return this.uint32(t)._push(YP,t,e)};Be.prototype.string=function(e){var t=Cg.length(e);return t?this.uint32(t)._push(Cg.write,t,e):this._push(Vp,1,0)};Be.prototype.fork=function(){return this.states=new GP(this),this.head=this.tail=new hu(qp,0,0),this.len=0,this};Be.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 hu(qp,0,0),this.len=0),this};Be.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};Be.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};Be._configure=function(r){Fp=r,Be.create=Pg(),Fp._configure()}});var Og=T((vQ,Lg)=>{"use strict";Lg.exports=di;var Ng=$p();(di.prototype=Object.create(Ng.prototype)).constructor=di;var bs=vo();function di(){Ng.call(this)}di._configure=function(){di.alloc=bs._Buffer_allocUnsafe,di.writeBytesBuffer=bs.Buffer&&bs.Buffer.prototype instanceof Uint8Array&&bs.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<e.length;)t[n++]=e[i++]}};di.prototype.bytes=function(e){bs.isString(e)&&(e=bs._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(di.writeBytesBuffer,t,e),this};function QP(r,e,t){r.length<40?bs.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}di.prototype.string=function(e){var t=bs.Buffer.byteLength(e);return this.uint32(t),t&&this._push(QP,t,e),this};di._configure()});var jg=T((ZX,Xg)=>{"use strict";Xg.exports=function(){return Date.now()}});var Jg=T((JX,Zg)=>{"use strict";var Nh=jg(),Jp=class{constructor(e,t,n){let i=this;this._started=Nh(),this._rescheduled=0,this._scheduled=t,this._args=n,this._triggered=!1,this._timerWrapper=()=>{i._rescheduled>0?(i._scheduled=i._rescheduled-(Nh()-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=Nh();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=Nh(),this._rescheduled=0,this._scheduled=e,this._timer=setTimeout(this._timerWrapper,e)}clear(){clearTimeout(this._timer)}};function mk(){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<r.length;e++)r[e]=arguments[e+2]}return new Jp(arguments[0],arguments[1],r)}Zg.exports=mk});var ry=T((ej,ty)=>{"use strict";var{AbortController:gk}=globalThis,ey=Jg(),pu=class extends gk{constructor(e){super(),this._ms=e,this._timer=ey(()=>this.abort(),e),Object.setPrototypeOf(this,pu.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=ey(()=>this.abort(),this._ms)}};ty.exports={TimeoutController:pu}});var Zr=T((hj,i2)=>{"use strict";var va=typeof Reflect=="object"?Reflect:null,ay=va&&typeof va.apply=="function"?va.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},Oh;va&&typeof va.ownKeys=="function"?Oh=va.ownKeys:Object.getOwnPropertySymbols?Oh=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Oh=function(e){return Object.getOwnPropertyNames(e)};function vk(r){console&&console.warn&&console.warn(r)}var uy=Number.isNaN||function(e){return e!==e};function st(){st.init.call(this)}i2.exports=st;i2.exports.once=Ak;st.EventEmitter=st;st.prototype._events=void 0;st.prototype._eventsCount=0;st.prototype._maxListeners=void 0;var cy=10;function Bh(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(st,"defaultMaxListeners",{enumerable:!0,get:function(){return cy},set:function(r){if(typeof r!="number"||r<0||uy(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");cy=r}});st.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};st.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||uy(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 ly(r){return r._maxListeners===void 0?st.defaultMaxListeners:r._maxListeners}st.prototype.getMaxListeners=function(){return ly(this)};st.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")ay(c,this,t);else for(var u=c.length,l=my(c,u),n=0;n<u;++n)ay(l[n],this,t);return!0};function hy(r,e,t,n){var i,s,o;if(Bh(t),s=r._events,s===void 0?(s=r._events=Object.create(null),r._eventsCount=0):(s.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),s=r._events),o=s[e]),o===void 0)o=s[e]=t,++r._eventsCount;else if(typeof o=="function"?o=s[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),i=ly(r),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,vk(a)}return r}st.prototype.addListener=function(e,t){return hy(this,e,t,!1)};st.prototype.on=st.prototype.addListener;st.prototype.prependListener=function(e,t){return hy(this,e,t,!0)};function xk(){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 fy(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=xk.bind(n);return i.listener=t,n.wrapFn=i,i}st.prototype.once=function(e,t){return Bh(t),this.on(e,fy(this,e,t)),this};st.prototype.prependOnceListener=function(e,t){return Bh(t),this.prependListener(e,fy(this,e,t)),this};st.prototype.removeListener=function(e,t){var n,i,s,o,a;if(Bh(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(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():_k(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};st.prototype.off=st.prototype.removeListener;st.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 s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function dy(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?Sk(i):my(i,i.length)}st.prototype.listeners=function(e){return dy(this,e,!0)};st.prototype.rawListeners=function(e){return dy(this,e,!1)};st.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):py.call(r,e)};st.prototype.listenerCount=py;function py(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}st.prototype.eventNames=function(){return this._eventsCount>0?Oh(this._events):[]};function my(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function _k(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Sk(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Ak(r,e){return new Promise(function(t,n){function i(o){r.removeListener(e,s),n(o)}function s(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}gy(r,e,s,{once:!0}),e!=="error"&&Rk(r,i,{once:!0})})}function Rk(r,e,t){typeof r.on=="function"&&gy(r,"error",e,t)}function gy(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(s){n.once&&r.removeEventListener(e,i),t(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var xy=T((Ey,vy)=>{"use strict";var Ik=Math.exp;Ey=vy.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,s=0,o,a={};function c(u,l){return 1-Ik(-(u-l)/e)}return a.push=function(l,h){if(o){let f=c(l,o),d=h-t,p=f*d;t=f*h+(1-f)*t,n=(1-f)*(n+d*p),i=Math.sqrt(n),s=t+f*d}else t=h;o=l},a.movingAverage=function(){return t},a.variance=function(){return n},a.deviation=function(){return i},a.forecast=function(){return s},a}});var L7=T((zZ,d2)=>{"use strict";var sN=Object.prototype.hasOwnProperty,Dr="~";function _u(){}Object.create&&(_u.prototype=Object.create(null),new _u().__proto__||(Dr=!1));function oN(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function N7(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new oN(t,n||r,i),o=Dr?Dr+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function ef(r,e){--r._eventsCount===0?r._events=new _u:delete r._events[e]}function vr(){this._events=new _u,this._eventsCount=0}vr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)sN.call(t,n)&&e.push(Dr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};vr.prototype.listeners=function(e){var t=Dr?Dr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};vr.prototype.listenerCount=function(e){var t=Dr?Dr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};vr.prototype.emit=function(e,t,n,i,s,o){var a=Dr?Dr+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,o),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var f=c.length,d;for(h=0;h<f;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[h].fn.apply(c[h].context,l)}}return!0};vr.prototype.on=function(e,t,n){return N7(this,e,t,n,!1)};vr.prototype.once=function(e,t,n){return N7(this,e,t,n,!0)};vr.prototype.removeListener=function(e,t,n,i){var s=Dr?Dr+e:e;if(!this._events[s])return this;if(!t)return ef(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&ef(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==t||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:ef(this,s)}return this};vr.prototype.removeAllListeners=function(e){var t;return e?(t=Dr?Dr+e:e,this._events[t]&&ef(this,t)):(this._events=new _u,this._eventsCount=0),this};vr.prototype.off=vr.prototype.removeListener;vr.prototype.addListener=vr.prototype.on;vr.prefixed=Dr;vr.EventEmitter=vr;typeof d2<"u"&&(d2.exports=vr)});var m9=T((Iee,p9)=>{"use strict";p9.exports=tr;var Nu=Ds();function tr(r,e){this.lo=r>>>0,this.hi=e>>>0}var Io=tr.zero=new tr(0,0);Io.toNumber=function(){return 0};Io.zzEncode=Io.zzDecode=function(){return this};Io.length=function(){return 1};var wN=tr.zeroHash="\0\0\0\0\0\0\0\0";tr.fromNumber=function(e){if(e===0)return Io;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 tr(n,i)};tr.from=function(e){if(typeof e=="number")return tr.fromNumber(e);if(Nu.isString(e))if(Nu.Long)e=Nu.Long.fromString(e);else return tr.fromNumber(parseInt(e,10));return e.low||e.high?new tr(e.low>>>0,e.high>>>0):Io};tr.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};tr.prototype.toLong=function(e){return Nu.Long?new Nu.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Ts=String.prototype.charCodeAt;tr.fromHash=function(e){return e===wN?Io:new tr((Ts.call(e,0)|Ts.call(e,1)<<8|Ts.call(e,2)<<16|Ts.call(e,3)<<24)>>>0,(Ts.call(e,4)|Ts.call(e,5)<<8|Ts.call(e,6)<<16|Ts.call(e,7)<<24)>>>0)};tr.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)};tr.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};tr.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};tr.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 Ds=T(K2=>{"use strict";var J=K2;J.asPromise=Ip();J.base64=Tp();J.EventEmitter=Dp();J.float=Cp();J.inquire=Pp();J.utf8=Np();J.pool=Lp();J.LongBits=m9();J.isNode=!!(typeof globalThis<"u"&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node);J.global=J.isNode&&globalThis||typeof window<"u"&&window||typeof self<"u"&&self||K2;J.emptyArray=Object.freeze?Object.freeze([]):[];J.emptyObject=Object.freeze?Object.freeze({}):{};J.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};J.isString=function(e){return typeof e=="string"||e instanceof String};J.isObject=function(e){return e&&typeof e=="object"};J.isset=J.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};J.Buffer=function(){try{var r=J.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();J._Buffer_from=null;J._Buffer_allocUnsafe=null;J.newBuffer=function(e){return typeof e=="number"?J.Buffer?J._Buffer_allocUnsafe(e):new J.Array(e):J.Buffer?J._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};J.Array=typeof Uint8Array<"u"?Uint8Array:Array;J.Long=J.global.dcodeIO&&J.global.dcodeIO.Long||J.global.Long||J.inquire("long");J.key2Re=/^true|false|0|1$/;J.key32Re=/^-?(?:0|[1-9][0-9]*)$/;J.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;J.longToHash=function(e){return e?J.LongBits.from(e).toHash():J.LongBits.zeroHash};J.longFromHash=function(e,t){var n=J.LongBits.fromHash(e);return J.Long?J.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function g9(r,e,t){for(var n=Object.keys(e),i=0;i<n.length;++i)(r[n[i]]===void 0||!t)&&(r[n[i]]=e[n[i]]);return r}J.merge=g9;J.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function y9(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&g9(this,n)}return(e.prototype=Object.create(Error.prototype)).constructor=e,Object.defineProperty(e.prototype,"name",{get:function(){return r}}),e.prototype.toString=function(){return this.name+": "+this.message},e}J.newError=y9;J.ProtocolError=y9("ProtocolError");J.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var i=Object.keys(this),s=i.length-1;s>-1;--s)if(t[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};J.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};J.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};J._configure=function(){var r=J.Buffer;if(!r){J._Buffer_from=J._Buffer_allocUnsafe=null;return}J._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},J._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var W2=T((Dee,v9)=>{"use strict";v9.exports=Fe;var Rn=Ds(),q2,gf=Rn.LongBits,w9=Rn.base64,b9=Rn.utf8;function Lu(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function z2(){}function bN(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function Fe(){this.len=0,this.head=new Lu(z2,0,0),this.tail=this.head,this.states=null}var E9=function(){return Rn.Buffer?function(){return(Fe.create=function(){return new q2})()}:function(){return new Fe}};Fe.create=E9();Fe.alloc=function(e){return new Rn.Array(e)};Rn.Array!==Array&&(Fe.alloc=Rn.pool(Fe.alloc,Rn.Array.prototype.subarray));Fe.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Lu(e,t,n),this.len+=t,this};function H2(r,e,t){e[t]=r&255}function EN(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function $2(r,e){this.len=r,this.next=void 0,this.val=e}$2.prototype=Object.create(Lu.prototype);$2.prototype.fn=EN;Fe.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new $2((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Fe.prototype.int32=function(e){return e<0?this._push(G2,10,gf.fromNumber(e)):this.uint32(e)};Fe.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function G2(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}Fe.prototype.uint64=function(e){var t=gf.from(e);return this._push(G2,t.length(),t)};Fe.prototype.int64=Fe.prototype.uint64;Fe.prototype.sint64=function(e){var t=gf.from(e).zzEncode();return this._push(G2,t.length(),t)};Fe.prototype.bool=function(e){return this._push(H2,1,e?1:0)};function V2(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}Fe.prototype.fixed32=function(e){return this._push(V2,4,e>>>0)};Fe.prototype.sfixed32=Fe.prototype.fixed32;Fe.prototype.fixed64=function(e){var t=gf.from(e);return this._push(V2,4,t.lo)._push(V2,4,t.hi)};Fe.prototype.sfixed64=Fe.prototype.fixed64;Fe.prototype.float=function(e){return this._push(Rn.float.writeFloatLE,4,e)};Fe.prototype.double=function(e){return this._push(Rn.float.writeDoubleLE,8,e)};var vN=Rn.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i<e.length;++i)t[n+i]=e[i]};Fe.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(H2,1,0);if(Rn.isString(e)){var n=Fe.alloc(t=w9.length(e));w9.decode(e,n,0),e=n}return this.uint32(t)._push(vN,t,e)};Fe.prototype.string=function(e){var t=b9.length(e);return t?this.uint32(t)._push(b9.write,t,e):this._push(H2,1,0)};Fe.prototype.fork=function(){return this.states=new bN(this),this.head=this.tail=new Lu(z2,0,0),this.len=0,this};Fe.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 Lu(z2,0,0),this.len=0),this};Fe.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};Fe.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};Fe._configure=function(r){q2=r,Fe.create=E9(),q2._configure()}});var S9=T((Cee,_9)=>{"use strict";_9.exports=gi;var x9=W2();(gi.prototype=Object.create(x9.prototype)).constructor=gi;var Cs=Ds();function gi(){x9.call(this)}gi._configure=function(){gi.alloc=Cs._Buffer_allocUnsafe,gi.writeBytesBuffer=Cs.Buffer&&Cs.Buffer.prototype instanceof Uint8Array&&Cs.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<e.length;)t[n++]=e[i++]}};gi.prototype.bytes=function(e){Cs.isString(e)&&(e=Cs._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(gi.writeBytesBuffer,t,e),this};function xN(r,e,t){r.length<40?Cs.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}gi.prototype.string=function(e){var t=Cs.Buffer.byteLength(e);return this.uint32(t),t&&this._push(xN,t,e),this};gi._configure()});var X2=T((Pee,D9)=>{"use strict";D9.exports=Ut;var yi=Ds(),Q2,I9=yi.LongBits,_N=yi.utf8;function Gn(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function Ut(r){this.buf=r,this.pos=0,this.len=r.length}var A9=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Ut(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Ut(e);throw Error("illegal buffer")},T9=function(){return yi.Buffer?function(t){return(Ut.create=function(i){return yi.Buffer.isBuffer(i)?new Q2(i):A9(i)})(t)}:A9};Ut.create=T9();Ut.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Ut.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,Gn(this,10);return e}}();Ut.prototype.int32=function(){return this.uint32()|0};Ut.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Y2(){var r=new I9(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>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 Gn(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw Gn(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}Ut.prototype.bool=function(){return this.uint32()!==0};function yf(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}Ut.prototype.fixed32=function(){if(this.pos+4>this.len)throw Gn(this,4);return yf(this.buf,this.pos+=4)};Ut.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Gn(this,4);return yf(this.buf,this.pos+=4)|0};function R9(){if(this.pos+8>this.len)throw Gn(this,8);return new I9(yf(this.buf,this.pos+=4),yf(this.buf,this.pos+=4))}Ut.prototype.float=function(){if(this.pos+4>this.len)throw Gn(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Ut.prototype.double=function(){if(this.pos+8>this.len)throw Gn(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Ut.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Gn(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)};Ut.prototype.string=function(){var e=this.bytes();return _N.read(e,0,e.length)};Ut.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Gn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Gn(this);while(this.buf[this.pos++]&128);return this};Ut.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};Ut._configure=function(r){Q2=r,Ut.create=T9(),Q2._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Ut.prototype,{int64:function(){return Y2.call(this)[e](!1)},uint64:function(){return Y2.call(this)[e](!0)},sint64:function(){return Y2.call(this).zzDecode()[e](!1)},fixed64:function(){return R9.call(this)[e](!0)},sfixed64:function(){return R9.call(this)[e](!1)}})}});var N9=T((kee,k9)=>{"use strict";k9.exports=To;var P9=X2();(To.prototype=Object.create(P9.prototype)).constructor=To;var C9=Ds();function To(r){P9.call(this,r)}To._configure=function(){C9.Buffer&&(To.prototype._slice=C9.Buffer.prototype.slice)};To.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))};To._configure()});var O9=T((Nee,L9)=>{"use strict";L9.exports=Ou;var j2=Ds();(Ou.prototype=Object.create(j2.EventEmitter.prototype)).constructor=Ou;function Ou(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");j2.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Ou.prototype.rpcCall=function r(e,t,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return j2.asPromise(r,o,e,t,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,t[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(c,u){if(c)return o.emit("error",c,e),s(c);if(u===null){o.end(!0);return}if(!(u instanceof n))try{u=n[o.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return o.emit("error",l,e),s(l)}return o.emit("data",u,e),s(null,u)})}catch(a){o.emit("error",a,e),setTimeout(function(){s(a)},0);return}};Ou.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var M9=T(B9=>{"use strict";var SN=B9;SN.Service=O9()});var F9=T((Oee,U9)=>{"use strict";U9.exports={}});var V9=T(q9=>{"use strict";var qr=q9;qr.build="minimal";qr.Writer=W2();qr.BufferWriter=S9();qr.Reader=X2();qr.BufferReader=N9();qr.util=Ds();qr.rpc=M9();qr.roots=F9();qr.configure=K9;function K9(){qr.util._configure(),qr.Writer._configure(qr.BufferWriter),qr.Reader._configure(qr.BufferReader)}K9()});var Z2=T((Mee,z9)=>{"use strict";z9.exports=V9()});var $9=T((H9,Bu)=>{(function(r,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof sh=="function"&&typeof Bu=="object"&&Bu&&Bu.exports&&(Bu.exports=e(Z2()))})(H9,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 s(a){if(this.subscriptions=[],this.messages=[],a)for(var c=Object.keys(a),u=0;u<c.length;++u)a[c[u]]!=null&&(this[c[u]]=a[c[u]])}s.prototype.subscriptions=n.emptyArray,s.prototype.messages=n.emptyArray,s.prototype.control=null;var o;return Object.defineProperty(s.prototype,"_control",{get:n.oneOfGetter(o=["control"]),set:n.oneOfSetter(o)}),s.encode=function(c,u){if(u||(u=t.create()),c.subscriptions!=null&&c.subscriptions.length)for(var l=0;l<c.subscriptions.length;++l)i.RPC.SubOpts.encode(c.subscriptions[l],u.uint32(10).fork()).ldelim();if(c.messages!=null&&c.messages.length)for(var l=0;l<c.messages.length;++l)i.RPC.Message.encode(c.messages[l],u.uint32(18).fork()).ldelim();return c.control!=null&&Object.hasOwnProperty.call(c,"control")&&i.RPC.ControlMessage.encode(c.control,u.uint32(26).fork()).ldelim(),u},s.decode=function(c,u){c instanceof e||(c=e.create(c));for(var l=u===void 0?c.len:c.pos+u,h=new i.RPC;c.pos<l;){var f=c.uint32();switch(f>>>3){case 1:h.subscriptions&&h.subscriptions.length||(h.subscriptions=[]),h.subscriptions.push(i.RPC.SubOpts.decode(c,c.uint32()));break;case 2:h.messages&&h.messages.length||(h.messages=[]),h.messages.push(i.RPC.Message.decode(c,c.uint32()));break;case 3:h.control=i.RPC.ControlMessage.decode(c,c.uint32());break;default:c.skipType(f&7);break}}return h},s.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<c.subscriptions.length;++l){if(typeof c.subscriptions[l]!="object")throw TypeError(".RPC.subscriptions: object expected");u.subscriptions[l]=i.RPC.SubOpts.fromObject(c.subscriptions[l])}}if(c.messages){if(!Array.isArray(c.messages))throw TypeError(".RPC.messages: array expected");u.messages=[];for(var l=0;l<c.messages.length;++l){if(typeof c.messages[l]!="object")throw TypeError(".RPC.messages: object expected");u.messages[l]=i.RPC.Message.fromObject(c.messages[l])}}if(c.control!=null){if(typeof c.control!="object")throw TypeError(".RPC.control: object expected");u.control=i.RPC.ControlMessage.fromObject(c.control)}return u},s.toObject=function(c,u){u||(u={});var l={};if((u.arrays||u.defaults)&&(l.subscriptions=[],l.messages=[]),c.subscriptions&&c.subscriptions.length){l.subscriptions=[];for(var h=0;h<c.subscriptions.length;++h)l.subscriptions[h]=i.RPC.SubOpts.toObject(c.subscriptions[h],u)}if(c.messages&&c.messages.length){l.messages=[];for(var h=0;h<c.messages.length;++h)l.messages[h]=i.RPC.Message.toObject(c.messages[h],u)}return c.control!=null&&c.hasOwnProperty("control")&&(l.control=i.RPC.ControlMessage.toObject(c.control,u),u.oneofs&&(l._control="control")),l},s.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},s.SubOpts=function(){function a(u){if(u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.subscribe=null,a.prototype.topic=null;var c;return Object.defineProperty(a.prototype,"_subscribe",{get:n.oneOfGetter(c=["subscribe"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_topic",{get:n.oneOfGetter(c=["topic"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){return h||(h=t.create()),l.subscribe!=null&&Object.hasOwnProperty.call(l,"subscribe")&&h.uint32(8).bool(l.subscribe),l.topic!=null&&Object.hasOwnProperty.call(l,"topic")&&h.uint32(18).string(l.topic),h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.SubOpts;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.SubOpts;return l.subscribe!=null&&(h.subscribe=!!l.subscribe),l.topic!=null&&(h.topic=String(l.topic)),h},a.toObject=function(l,h){h||(h={});var f={};return l.subscribe!=null&&l.hasOwnProperty("subscribe")&&(f.subscribe=l.subscribe,h.oneofs&&(f._subscribe="subscribe")),l.topic!=null&&l.hasOwnProperty("topic")&&(f.topic=l.topic,h.oneofs&&(f._topic="topic")),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.Message=function(){function a(u){if(u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.from=null,a.prototype.data=null,a.prototype.seqno=null,a.prototype.topic="",a.prototype.signature=null,a.prototype.key=null;var c;return Object.defineProperty(a.prototype,"_from",{get:n.oneOfGetter(c=["from"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_data",{get:n.oneOfGetter(c=["data"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_seqno",{get:n.oneOfGetter(c=["seqno"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_signature",{get:n.oneOfGetter(c=["signature"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_key",{get:n.oneOfGetter(c=["key"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){return h||(h=t.create()),l.from!=null&&Object.hasOwnProperty.call(l,"from")&&h.uint32(10).bytes(l.from),l.data!=null&&Object.hasOwnProperty.call(l,"data")&&h.uint32(18).bytes(l.data),l.seqno!=null&&Object.hasOwnProperty.call(l,"seqno")&&h.uint32(26).bytes(l.seqno),h.uint32(34).string(l.topic),l.signature!=null&&Object.hasOwnProperty.call(l,"signature")&&h.uint32(42).bytes(l.signature),l.key!=null&&Object.hasOwnProperty.call(l,"key")&&h.uint32(50).bytes(l.key),h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.Message;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.Message;return l.from!=null&&(typeof l.from=="string"?n.base64.decode(l.from,h.from=n.newBuffer(n.base64.length(l.from)),0):l.from.length&&(h.from=l.from)),l.data!=null&&(typeof l.data=="string"?n.base64.decode(l.data,h.data=n.newBuffer(n.base64.length(l.data)),0):l.data.length&&(h.data=l.data)),l.seqno!=null&&(typeof l.seqno=="string"?n.base64.decode(l.seqno,h.seqno=n.newBuffer(n.base64.length(l.seqno)),0):l.seqno.length&&(h.seqno=l.seqno)),l.topic!=null&&(h.topic=String(l.topic)),l.signature!=null&&(typeof l.signature=="string"?n.base64.decode(l.signature,h.signature=n.newBuffer(n.base64.length(l.signature)),0):l.signature.length&&(h.signature=l.signature)),l.key!=null&&(typeof l.key=="string"?n.base64.decode(l.key,h.key=n.newBuffer(n.base64.length(l.key)),0):l.key.length&&(h.key=l.key)),h},a.toObject=function(l,h){h||(h={});var f={};return h.defaults&&(f.topic=""),l.from!=null&&l.hasOwnProperty("from")&&(f.from=h.bytes===String?n.base64.encode(l.from,0,l.from.length):h.bytes===Array?Array.prototype.slice.call(l.from):l.from,h.oneofs&&(f._from="from")),l.data!=null&&l.hasOwnProperty("data")&&(f.data=h.bytes===String?n.base64.encode(l.data,0,l.data.length):h.bytes===Array?Array.prototype.slice.call(l.data):l.data,h.oneofs&&(f._data="data")),l.seqno!=null&&l.hasOwnProperty("seqno")&&(f.seqno=h.bytes===String?n.base64.encode(l.seqno,0,l.seqno.length):h.bytes===Array?Array.prototype.slice.call(l.seqno):l.seqno,h.oneofs&&(f._seqno="seqno")),l.topic!=null&&l.hasOwnProperty("topic")&&(f.topic=l.topic),l.signature!=null&&l.hasOwnProperty("signature")&&(f.signature=h.bytes===String?n.base64.encode(l.signature,0,l.signature.length):h.bytes===Array?Array.prototype.slice.call(l.signature):l.signature,h.oneofs&&(f._signature="signature")),l.key!=null&&l.hasOwnProperty("key")&&(f.key=h.bytes===String?n.base64.encode(l.key,0,l.key.length):h.bytes===Array?Array.prototype.slice.call(l.key):l.key,h.oneofs&&(f._key="key")),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlMessage=function(){function a(c){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],c)for(var u=Object.keys(c),l=0;l<u.length;++l)c[u[l]]!=null&&(this[u[l]]=c[u[l]])}return a.prototype.ihave=n.emptyArray,a.prototype.iwant=n.emptyArray,a.prototype.graft=n.emptyArray,a.prototype.prune=n.emptyArray,a.encode=function(u,l){if(l||(l=t.create()),u.ihave!=null&&u.ihave.length)for(var h=0;h<u.ihave.length;++h)i.RPC.ControlIHave.encode(u.ihave[h],l.uint32(10).fork()).ldelim();if(u.iwant!=null&&u.iwant.length)for(var h=0;h<u.iwant.length;++h)i.RPC.ControlIWant.encode(u.iwant[h],l.uint32(18).fork()).ldelim();if(u.graft!=null&&u.graft.length)for(var h=0;h<u.graft.length;++h)i.RPC.ControlGraft.encode(u.graft[h],l.uint32(26).fork()).ldelim();if(u.prune!=null&&u.prune.length)for(var h=0;h<u.prune.length;++h)i.RPC.ControlPrune.encode(u.prune[h],l.uint32(34).fork()).ldelim();return l},a.decode=function(u,l){u instanceof e||(u=e.create(u));for(var h=l===void 0?u.len:u.pos+l,f=new i.RPC.ControlMessage;u.pos<h;){var d=u.uint32();switch(d>>>3){case 1:f.ihave&&f.ihave.length||(f.ihave=[]),f.ihave.push(i.RPC.ControlIHave.decode(u,u.uint32()));break;case 2:f.iwant&&f.iwant.length||(f.iwant=[]),f.iwant.push(i.RPC.ControlIWant.decode(u,u.uint32()));break;case 3:f.graft&&f.graft.length||(f.graft=[]),f.graft.push(i.RPC.ControlGraft.decode(u,u.uint32()));break;case 4:f.prune&&f.prune.length||(f.prune=[]),f.prune.push(i.RPC.ControlPrune.decode(u,u.uint32()));break;default:u.skipType(d&7);break}}return f},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 h=0;h<u.ihave.length;++h){if(typeof u.ihave[h]!="object")throw TypeError(".RPC.ControlMessage.ihave: object expected");l.ihave[h]=i.RPC.ControlIHave.fromObject(u.ihave[h])}}if(u.iwant){if(!Array.isArray(u.iwant))throw TypeError(".RPC.ControlMessage.iwant: array expected");l.iwant=[];for(var h=0;h<u.iwant.length;++h){if(typeof u.iwant[h]!="object")throw TypeError(".RPC.ControlMessage.iwant: object expected");l.iwant[h]=i.RPC.ControlIWant.fromObject(u.iwant[h])}}if(u.graft){if(!Array.isArray(u.graft))throw TypeError(".RPC.ControlMessage.graft: array expected");l.graft=[];for(var h=0;h<u.graft.length;++h){if(typeof u.graft[h]!="object")throw TypeError(".RPC.ControlMessage.graft: object expected");l.graft[h]=i.RPC.ControlGraft.fromObject(u.graft[h])}}if(u.prune){if(!Array.isArray(u.prune))throw TypeError(".RPC.ControlMessage.prune: array expected");l.prune=[];for(var h=0;h<u.prune.length;++h){if(typeof u.prune[h]!="object")throw TypeError(".RPC.ControlMessage.prune: object expected");l.prune[h]=i.RPC.ControlPrune.fromObject(u.prune[h])}}return l},a.toObject=function(u,l){l||(l={});var h={};if((l.arrays||l.defaults)&&(h.ihave=[],h.iwant=[],h.graft=[],h.prune=[]),u.ihave&&u.ihave.length){h.ihave=[];for(var f=0;f<u.ihave.length;++f)h.ihave[f]=i.RPC.ControlIHave.toObject(u.ihave[f],l)}if(u.iwant&&u.iwant.length){h.iwant=[];for(var f=0;f<u.iwant.length;++f)h.iwant[f]=i.RPC.ControlIWant.toObject(u.iwant[f],l)}if(u.graft&&u.graft.length){h.graft=[];for(var f=0;f<u.graft.length;++f)h.graft[f]=i.RPC.ControlGraft.toObject(u.graft[f],l)}if(u.prune&&u.prune.length){h.prune=[];for(var f=0;f<u.prune.length;++f)h.prune[f]=i.RPC.ControlPrune.toObject(u.prune[f],l)}return h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlIHave=function(){function a(u){if(this.messageIDs=[],u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.topicID=null,a.prototype.messageIDs=n.emptyArray;var c;return Object.defineProperty(a.prototype,"_topicID",{get:n.oneOfGetter(c=["topicID"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){if(h||(h=t.create()),l.topicID!=null&&Object.hasOwnProperty.call(l,"topicID")&&h.uint32(10).string(l.topicID),l.messageIDs!=null&&l.messageIDs.length)for(var f=0;f<l.messageIDs.length;++f)h.uint32(18).bytes(l.messageIDs[f]);return h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.ControlIHave;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.ControlIHave;if(l.topicID!=null&&(h.topicID=String(l.topicID)),l.messageIDs){if(!Array.isArray(l.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");h.messageIDs=[];for(var f=0;f<l.messageIDs.length;++f)typeof l.messageIDs[f]=="string"?n.base64.decode(l.messageIDs[f],h.messageIDs[f]=n.newBuffer(n.base64.length(l.messageIDs[f])),0):l.messageIDs[f].length&&(h.messageIDs[f]=l.messageIDs[f])}return h},a.toObject=function(l,h){h||(h={});var f={};if((h.arrays||h.defaults)&&(f.messageIDs=[]),l.topicID!=null&&l.hasOwnProperty("topicID")&&(f.topicID=l.topicID,h.oneofs&&(f._topicID="topicID")),l.messageIDs&&l.messageIDs.length){f.messageIDs=[];for(var d=0;d<l.messageIDs.length;++d)f.messageIDs[d]=h.bytes===String?n.base64.encode(l.messageIDs[d],0,l.messageIDs[d].length):h.bytes===Array?Array.prototype.slice.call(l.messageIDs[d]):l.messageIDs[d]}return f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlIWant=function(){function a(c){if(this.messageIDs=[],c)for(var u=Object.keys(c),l=0;l<u.length;++l)c[u[l]]!=null&&(this[u[l]]=c[u[l]])}return a.prototype.messageIDs=n.emptyArray,a.encode=function(u,l){if(l||(l=t.create()),u.messageIDs!=null&&u.messageIDs.length)for(var h=0;h<u.messageIDs.length;++h)l.uint32(10).bytes(u.messageIDs[h]);return l},a.decode=function(u,l){u instanceof e||(u=e.create(u));for(var h=l===void 0?u.len:u.pos+l,f=new i.RPC.ControlIWant;u.pos<h;){var d=u.uint32();switch(d>>>3){case 1:f.messageIDs&&f.messageIDs.length||(f.messageIDs=[]),f.messageIDs.push(u.bytes());break;default:u.skipType(d&7);break}}return f},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 h=0;h<u.messageIDs.length;++h)typeof u.messageIDs[h]=="string"?n.base64.decode(u.messageIDs[h],l.messageIDs[h]=n.newBuffer(n.base64.length(u.messageIDs[h])),0):u.messageIDs[h].length&&(l.messageIDs[h]=u.messageIDs[h])}return l},a.toObject=function(u,l){l||(l={});var h={};if((l.arrays||l.defaults)&&(h.messageIDs=[]),u.messageIDs&&u.messageIDs.length){h.messageIDs=[];for(var f=0;f<u.messageIDs.length;++f)h.messageIDs[f]=l.bytes===String?n.base64.encode(u.messageIDs[f],0,u.messageIDs[f].length):l.bytes===Array?Array.prototype.slice.call(u.messageIDs[f]):u.messageIDs[f]}return h},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlGraft=function(){function a(u){if(u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.topicID=null;var c;return Object.defineProperty(a.prototype,"_topicID",{get:n.oneOfGetter(c=["topicID"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){return h||(h=t.create()),l.topicID!=null&&Object.hasOwnProperty.call(l,"topicID")&&h.uint32(10).string(l.topicID),h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.ControlGraft;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.ControlGraft;return l.topicID!=null&&(h.topicID=String(l.topicID)),h},a.toObject=function(l,h){h||(h={});var f={};return l.topicID!=null&&l.hasOwnProperty("topicID")&&(f.topicID=l.topicID,h.oneofs&&(f._topicID="topicID")),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.ControlPrune=function(){function a(u){if(this.peers=[],u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.topicID=null,a.prototype.peers=n.emptyArray,a.prototype.backoff=null;var c;return Object.defineProperty(a.prototype,"_topicID",{get:n.oneOfGetter(c=["topicID"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_backoff",{get:n.oneOfGetter(c=["backoff"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){if(h||(h=t.create()),l.topicID!=null&&Object.hasOwnProperty.call(l,"topicID")&&h.uint32(10).string(l.topicID),l.peers!=null&&l.peers.length)for(var f=0;f<l.peers.length;++f)i.RPC.PeerInfo.encode(l.peers[f],h.uint32(18).fork()).ldelim();return l.backoff!=null&&Object.hasOwnProperty.call(l,"backoff")&&h.uint32(24).uint64(l.backoff),h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.ControlPrune;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.ControlPrune;if(l.topicID!=null&&(h.topicID=String(l.topicID)),l.peers){if(!Array.isArray(l.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");h.peers=[];for(var f=0;f<l.peers.length;++f){if(typeof l.peers[f]!="object")throw TypeError(".RPC.ControlPrune.peers: object expected");h.peers[f]=i.RPC.PeerInfo.fromObject(l.peers[f])}}return l.backoff!=null&&(n.Long?(h.backoff=n.Long.fromValue(l.backoff)).unsigned=!0:typeof l.backoff=="string"?h.backoff=parseInt(l.backoff,10):typeof l.backoff=="number"?h.backoff=l.backoff:typeof l.backoff=="object"&&(h.backoff=new n.LongBits(l.backoff.low>>>0,l.backoff.high>>>0).toNumber(!0))),h},a.toObject=function(l,h){h||(h={});var f={};if((h.arrays||h.defaults)&&(f.peers=[]),l.topicID!=null&&l.hasOwnProperty("topicID")&&(f.topicID=l.topicID,h.oneofs&&(f._topicID="topicID")),l.peers&&l.peers.length){f.peers=[];for(var d=0;d<l.peers.length;++d)f.peers[d]=i.RPC.PeerInfo.toObject(l.peers[d],h)}return l.backoff!=null&&l.hasOwnProperty("backoff")&&(typeof l.backoff=="number"?f.backoff=h.longs===String?String(l.backoff):l.backoff:f.backoff=h.longs===String?n.Long.prototype.toString.call(l.backoff):h.longs===Number?new n.LongBits(l.backoff.low>>>0,l.backoff.high>>>0).toNumber(!0):l.backoff,h.oneofs&&(f._backoff="backoff")),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s.PeerInfo=function(){function a(u){if(u)for(var l=Object.keys(u),h=0;h<l.length;++h)u[l[h]]!=null&&(this[l[h]]=u[l[h]])}a.prototype.peerID=null,a.prototype.signedPeerRecord=null;var c;return Object.defineProperty(a.prototype,"_peerID",{get:n.oneOfGetter(c=["peerID"]),set:n.oneOfSetter(c)}),Object.defineProperty(a.prototype,"_signedPeerRecord",{get:n.oneOfGetter(c=["signedPeerRecord"]),set:n.oneOfSetter(c)}),a.encode=function(l,h){return h||(h=t.create()),l.peerID!=null&&Object.hasOwnProperty.call(l,"peerID")&&h.uint32(10).bytes(l.peerID),l.signedPeerRecord!=null&&Object.hasOwnProperty.call(l,"signedPeerRecord")&&h.uint32(18).bytes(l.signedPeerRecord),h},a.decode=function(l,h){l instanceof e||(l=e.create(l));for(var f=h===void 0?l.len:l.pos+h,d=new i.RPC.PeerInfo;l.pos<f;){var p=l.uint32();switch(p>>>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 h=new i.RPC.PeerInfo;return l.peerID!=null&&(typeof l.peerID=="string"?n.base64.decode(l.peerID,h.peerID=n.newBuffer(n.base64.length(l.peerID)),0):l.peerID.length&&(h.peerID=l.peerID)),l.signedPeerRecord!=null&&(typeof l.signedPeerRecord=="string"?n.base64.decode(l.signedPeerRecord,h.signedPeerRecord=n.newBuffer(n.base64.length(l.signedPeerRecord)),0):l.signedPeerRecord.length&&(h.signedPeerRecord=l.signedPeerRecord)),h},a.toObject=function(l,h){h||(h={});var f={};return l.peerID!=null&&l.hasOwnProperty("peerID")&&(f.peerID=h.bytes===String?n.base64.encode(l.peerID,0,l.peerID.length):h.bytes===Array?Array.prototype.slice.call(l.peerID):l.peerID,h.oneofs&&(f._peerID="peerID")),l.signedPeerRecord!=null&&l.hasOwnProperty("signedPeerRecord")&&(f.signedPeerRecord=h.bytes===String?n.base64.encode(l.signedPeerRecord,0,l.signedPeerRecord.length):h.bytes===Array?Array.prototype.slice.call(l.signedPeerRecord):l.signedPeerRecord,h.oneofs&&(f._signedPeerRecord="signedPeerRecord")),f},a.prototype.toJSON=function(){return this.constructor.toObject(this,r.util.toJSONOptions)},a}(),s}(),i})});var rt=T((zee,X9)=>{X9.exports={options:{usePureJavaScript:!1}}});var J9=T((Hee,Z9)=>{var r3={};Z9.exports=r3;var j9={};r3.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=RN(r,e);else{var i=0,s=e.length,o=e.charAt(0),a=[0];for(i=0;i<r.length;++i){for(var c=0,u=r[i];c<a.length;++c)u+=a[c]<<8,a[c]=u%s,u=u/s|0;for(;u>0;)a.push(u%s),u=u/s|0}for(i=0;r[i]===0&&i<r.length-1;++i)n+=o;for(i=a.length-1;i>=0;--i)n+=e[a[i]]}if(t){var l=new RegExp(".{1,"+t+"}","g");n=n.match(l).join(`\r
|
|
3
|
+
`)}return n};r3.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=j9[e];if(!t){t=j9[e]=[];for(var n=0;n<e.length;++n)t[e.charCodeAt(n)]=n}r=r.replace(/\s/g,"");for(var i=e.length,s=e.charAt(0),o=[0],n=0;n<r.length;n++){var a=t[r.charCodeAt(n)];if(a===void 0)return;for(var c=0,u=a;c<o.length;++c)u+=o[c]*i,o[c]=u&255,u>>=8;for(;u>0;)o.push(u&255),u>>=8}for(var l=0;r[l]===s&&l<r.length-1;++l)o.push(0);return typeof Buffer<"u"?Buffer.from(o.reverse()):new Uint8Array(o.reverse())};function RN(r,e){var t=0,n=e.length,i=e.charAt(0),s=[0];for(t=0;t<r.length();++t){for(var o=0,a=r.at(t);o<s.length;++o)a+=s[o]<<8,s[o]=a%n,a=a/n|0;for(;a>0;)s.push(a%n),a=a/n|0}var c="";for(t=0;r.at(t)===0&&t<r.length()-1;++t)c+=i;for(t=s.length-1;t>=0;--t)c+=e[s[t]];return c}});var Ft=T(($ee,nw)=>{var ew=rt(),tw=J9(),x=nw.exports=ew.util=ew.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){x.nextTick=process.nextTick,typeof setImmediate=="function"?x.setImmediate=setImmediate:x.setImmediate=x.nextTick;return}if(typeof setImmediate=="function"){x.setImmediate=function(){return setImmediate.apply(void 0,arguments)},x.nextTick=function(a){return setImmediate(a)};return}if(x.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 o=a,r="forge.setImmediate",e=[];x.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 s=x.setImmediate;x.setImmediate=function(c){Date.now()-t>15?(t=Date.now(),s(c)):(e.push(c),e.length===1&&i.setAttribute("a",n=!n))}}x.nextTick=x.setImmediate})();x.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;x.globalScope=function(){return x.isNodejs?globalThis:typeof self>"u"?window:self}();x.isArray=Array.isArray||function(r){return Object.prototype.toString.call(r)==="[object Array]"};x.isArrayBuffer=function(r){return typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer};x.isArrayBufferView=function(r){return r&&x.isArrayBuffer(r.buffer)&&r.byteLength!==void 0};function Uu(r){if(!(r===8||r===16||r===24||r===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+r)}x.ByteBuffer=n3;function n3(r){if(this.data="",this.read=0,typeof r=="string")this.data=r;else if(x.isArrayBuffer(r)||x.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;t<e.length;++t)this.putByte(e[t])}}else(r instanceof n3||typeof r=="object"&&typeof r.data=="string"&&typeof r.read=="number")&&(this.data=r.data,this.read=r.read);this._constructedStringLength=0}x.ByteStringBuffer=n3;var IN=4096;x.ByteStringBuffer.prototype._optimizeConstructedString=function(r){this._constructedStringLength+=r,this._constructedStringLength>IN&&(this.data.substr(0,1),this._constructedStringLength=0)};x.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};x.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};x.ByteStringBuffer.prototype.putByte=function(r){return this.putBytes(String.fromCharCode(r))};x.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};x.ByteStringBuffer.prototype.putBytes=function(r){return this.data+=r,this._optimizeConstructedString(r.length),this};x.ByteStringBuffer.prototype.putString=function(r){return this.putBytes(x.encodeUtf8(r))};x.ByteStringBuffer.prototype.putInt16=function(r){return this.putBytes(String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};x.ByteStringBuffer.prototype.putInt24=function(r){return this.putBytes(String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255))};x.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))};x.ByteStringBuffer.prototype.putInt16Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255))};x.ByteStringBuffer.prototype.putInt24Le=function(r){return this.putBytes(String.fromCharCode(r&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r>>16&255))};x.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))};x.ByteStringBuffer.prototype.putInt=function(r,e){Uu(e);var t="";do e-=8,t+=String.fromCharCode(r>>e&255);while(e>0);return this.putBytes(t)};x.ByteStringBuffer.prototype.putSignedInt=function(r,e){return r<0&&(r+=2<<e-1),this.putInt(r,e)};x.ByteStringBuffer.prototype.putBuffer=function(r){return this.putBytes(r.getBytes())};x.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};x.ByteStringBuffer.prototype.getInt16=function(){var r=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,r};x.ByteStringBuffer.prototype.getInt24=function(){var r=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,r};x.ByteStringBuffer.prototype.getInt32=function(){var r=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,r};x.ByteStringBuffer.prototype.getInt16Le=function(){var r=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,r};x.ByteStringBuffer.prototype.getInt24Le=function(){var r=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,r};x.ByteStringBuffer.prototype.getInt32Le=function(){var r=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,r};x.ByteStringBuffer.prototype.getInt=function(r){Uu(r);var e=0;do e=(e<<8)+this.data.charCodeAt(this.read++),r-=8;while(r>0);return e};x.ByteStringBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<<r-2;return e>=t&&(e-=t<<1),e};x.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};x.ByteStringBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};x.ByteStringBuffer.prototype.at=function(r){return this.data.charCodeAt(this.read+r)};x.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};x.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};x.ByteStringBuffer.prototype.copy=function(){var r=x.createBuffer(this.data);return r.read=this.read,r};x.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};x.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};x.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};x.ByteStringBuffer.prototype.toHex=function(){for(var r="",e=this.read;e<this.data.length;++e){var t=this.data.charCodeAt(e);t<16&&(r+="0"),r+=t.toString(16)}return r};x.ByteStringBuffer.prototype.toString=function(){return x.decodeUtf8(this.bytes())};function TN(r,e){e=e||{},this.read=e.readOffset||0,this.growSize=e.growSize||1024;var t=x.isArrayBuffer(r),n=x.isArrayBufferView(r);if(t||n){t?this.data=new DataView(r):this.data=new DataView(r.buffer,r.byteOffset,r.byteLength),this.write="writeOffset"in e?e.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,r!=null&&this.putBytes(r),"writeOffset"in e&&(this.write=e.writeOffset)}x.DataBuffer=TN;x.DataBuffer.prototype.length=function(){return this.write-this.read};x.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};x.DataBuffer.prototype.accommodate=function(r,e){if(this.length()>=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};x.DataBuffer.prototype.putByte=function(r){return this.accommodate(1),this.data.setUint8(this.write++,r),this};x.DataBuffer.prototype.fillWithByte=function(r,e){this.accommodate(e);for(var t=0;t<e;++t)this.data.setUint8(r);return this};x.DataBuffer.prototype.putBytes=function(r,e){if(x.isArrayBufferView(r)){var t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength),n=t.byteLength-t.byteOffset;this.accommodate(n);var i=new Uint8Array(this.data.buffer,this.write);return i.set(t),this.write+=n,this}if(x.isArrayBuffer(r)){var t=new Uint8Array(r);this.accommodate(t.byteLength);var i=new Uint8Array(this.data.buffer);return i.set(t,this.write),this.write+=t.byteLength,this}if(r instanceof x.DataBuffer||typeof r=="object"&&typeof r.read=="number"&&typeof r.write=="number"&&x.isArrayBufferView(r.data)){var t=new Uint8Array(r.data.byteLength,r.read,r.length());this.accommodate(t.byteLength);var i=new Uint8Array(r.data.byteLength,this.write);return i.set(t),this.write+=t.byteLength,this}if(r instanceof x.ByteStringBuffer&&(r=r.data,e="binary"),e=e||"binary",typeof r=="string"){var s;if(e==="hex")return this.accommodate(Math.ceil(r.length/2)),s=new Uint8Array(this.data.buffer,this.write),this.write+=x.binary.hex.decode(r,s,this.write),this;if(e==="base64")return this.accommodate(Math.ceil(r.length/4)*3),s=new Uint8Array(this.data.buffer,this.write),this.write+=x.binary.base64.decode(r,s,this.write),this;if(e==="utf8"&&(r=x.encodeUtf8(r),e="binary"),e==="binary"||e==="raw")return this.accommodate(r.length),s=new Uint8Array(this.data.buffer,this.write),this.write+=x.binary.raw.decode(s),this;if(e==="utf16")return this.accommodate(r.length*2),s=new Uint16Array(this.data.buffer,this.write),this.write+=x.text.utf16.encode(s),this;throw new Error("Invalid encoding: "+e)}throw Error("Invalid parameter: "+r)};x.DataBuffer.prototype.putBuffer=function(r){return this.putBytes(r),r.clear(),this};x.DataBuffer.prototype.putString=function(r){return this.putBytes(r,"utf16")};x.DataBuffer.prototype.putInt16=function(r){return this.accommodate(2),this.data.setInt16(this.write,r),this.write+=2,this};x.DataBuffer.prototype.putInt24=function(r){return this.accommodate(3),this.data.setInt16(this.write,r>>8&65535),this.data.setInt8(this.write,r>>16&255),this.write+=3,this};x.DataBuffer.prototype.putInt32=function(r){return this.accommodate(4),this.data.setInt32(this.write,r),this.write+=4,this};x.DataBuffer.prototype.putInt16Le=function(r){return this.accommodate(2),this.data.setInt16(this.write,r,!0),this.write+=2,this};x.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};x.DataBuffer.prototype.putInt32Le=function(r){return this.accommodate(4),this.data.setInt32(this.write,r,!0),this.write+=4,this};x.DataBuffer.prototype.putInt=function(r,e){Uu(e),this.accommodate(e/8);do e-=8,this.data.setInt8(this.write++,r>>e&255);while(e>0);return this};x.DataBuffer.prototype.putSignedInt=function(r,e){return Uu(e),this.accommodate(e/8),r<0&&(r+=2<<e-1),this.putInt(r,e)};x.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};x.DataBuffer.prototype.getInt16=function(){var r=this.data.getInt16(this.read);return this.read+=2,r};x.DataBuffer.prototype.getInt24=function(){var r=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,r};x.DataBuffer.prototype.getInt32=function(){var r=this.data.getInt32(this.read);return this.read+=4,r};x.DataBuffer.prototype.getInt16Le=function(){var r=this.data.getInt16(this.read,!0);return this.read+=2,r};x.DataBuffer.prototype.getInt24Le=function(){var r=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,r};x.DataBuffer.prototype.getInt32Le=function(){var r=this.data.getInt32(this.read,!0);return this.read+=4,r};x.DataBuffer.prototype.getInt=function(r){Uu(r);var e=0;do e=(e<<8)+this.data.getInt8(this.read++),r-=8;while(r>0);return e};x.DataBuffer.prototype.getSignedInt=function(r){var e=this.getInt(r),t=2<<r-2;return e>=t&&(e-=t<<1),e};x.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};x.DataBuffer.prototype.bytes=function(r){return typeof r>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+r)};x.DataBuffer.prototype.at=function(r){return this.data.getUint8(this.read+r)};x.DataBuffer.prototype.setAt=function(r,e){return this.data.setUint8(r,e),this};x.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};x.DataBuffer.prototype.copy=function(){return new x.DataBuffer(this)};x.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};x.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};x.DataBuffer.prototype.truncate=function(r){return this.write=Math.max(0,this.length()-r),this.read=Math.min(this.read,this.write),this};x.DataBuffer.prototype.toHex=function(){for(var r="",e=this.read;e<this.data.byteLength;++e){var t=this.data.getUint8(e);t<16&&(r+="0"),r+=t.toString(16)}return r};x.DataBuffer.prototype.toString=function(r){var e=new Uint8Array(this.data,this.read,this.length());if(r=r||"utf8",r==="binary"||r==="raw")return x.binary.raw.encode(e);if(r==="hex")return x.binary.hex.encode(e);if(r==="base64")return x.binary.base64.encode(e);if(r==="utf8")return x.text.utf8.decode(e);if(r==="utf16")return x.text.utf16.decode(e);throw new Error("Invalid encoding: "+r)};x.createBuffer=function(r,e){return e=e||"raw",r!==void 0&&e==="utf8"&&(r=x.encodeUtf8(r)),new x.ByteBuffer(r)};x.fillString=function(r,e){for(var t="";e>0;)e&1&&(t+=r),e>>>=1,e>0&&(r+=r);return t};x.xorBytes=function(r,e,t){for(var n="",i="",s="",o=0,a=0;t>0;--t,++o)i=r.charCodeAt(o)^e.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s,n};x.hexToBytes=function(r){var e="",t=0;for(r.length&!0&&(t=1,e+=String.fromCharCode(parseInt(r[0],16)));t<r.length;t+=2)e+=String.fromCharCode(parseInt(r.substr(t,2),16));return e};x.bytesToHex=function(r){return x.createBuffer(r).toHex()};x.int32ToBytes=function(r){return String.fromCharCode(r>>24&255)+String.fromCharCode(r>>16&255)+String.fromCharCode(r>>8&255)+String.fromCharCode(r&255)};var Ps="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ks=[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],rw="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";x.encode64=function(r,e){for(var t="",n="",i,s,o,a=0;a<r.length;)i=r.charCodeAt(a++),s=r.charCodeAt(a++),o=r.charCodeAt(a++),t+=Ps.charAt(i>>2),t+=Ps.charAt((i&3)<<4|s>>4),isNaN(s)?t+="==":(t+=Ps.charAt((s&15)<<2|o>>6),t+=isNaN(o)?"=":Ps.charAt(o&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r
|
|
4
|
+
`,t=t.substr(e));return n+=t,n};x.decode64=function(r){r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var e="",t,n,i,s,o=0;o<r.length;)t=ks[r.charCodeAt(o++)-43],n=ks[r.charCodeAt(o++)-43],i=ks[r.charCodeAt(o++)-43],s=ks[r.charCodeAt(o++)-43],e+=String.fromCharCode(t<<2|n>>4),i!==64&&(e+=String.fromCharCode((n&15)<<4|i>>2),s!==64&&(e+=String.fromCharCode((i&3)<<6|s)));return e};x.encodeUtf8=function(r){return unescape(encodeURIComponent(r))};x.decodeUtf8=function(r){return decodeURIComponent(escape(r))};x.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:tw.encode,decode:tw.decode}};x.binary.raw.encode=function(r){return String.fromCharCode.apply(null,r)};x.binary.raw.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,s=0;s<r.length;++s)n[i++]=r.charCodeAt(s);return e?i-t:n};x.binary.hex.encode=x.bytesToHex;x.binary.hex.decode=function(r,e,t){var n=e;n||(n=new Uint8Array(Math.ceil(r.length/2))),t=t||0;var i=0,s=t;for(r.length&1&&(i=1,n[s++]=parseInt(r[0],16));i<r.length;i+=2)n[s++]=parseInt(r.substr(i,2),16);return e?s-t:n};x.binary.base64.encode=function(r,e){for(var t="",n="",i,s,o,a=0;a<r.byteLength;)i=r[a++],s=r[a++],o=r[a++],t+=Ps.charAt(i>>2),t+=Ps.charAt((i&3)<<4|s>>4),isNaN(s)?t+="==":(t+=Ps.charAt((s&15)<<2|o>>6),t+=isNaN(o)?"=":Ps.charAt(o&63)),e&&t.length>e&&(n+=t.substr(0,e)+`\r
|
|
5
|
+
`,t=t.substr(e));return n+=t,n};x.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,s,o,a,c=0,u=t;c<r.length;)i=ks[r.charCodeAt(c++)-43],s=ks[r.charCodeAt(c++)-43],o=ks[r.charCodeAt(c++)-43],a=ks[r.charCodeAt(c++)-43],n[u++]=i<<2|s>>4,o!==64&&(n[u++]=(s&15)<<4|o>>2,a!==64&&(n[u++]=(o&3)<<6|a));return e?u-t:n.subarray(0,u)};x.binary.base58.encode=function(r,e){return x.binary.baseN.encode(r,rw,e)};x.binary.base58.decode=function(r,e){return x.binary.baseN.decode(r,rw,e)};x.text={utf8:{},utf16:{}};x.text.utf8.encode=function(r,e,t){r=x.encodeUtf8(r);var n=e;n||(n=new Uint8Array(r.length)),t=t||0;for(var i=t,s=0;s<r.length;++s)n[i++]=r.charCodeAt(s);return e?i-t:n};x.text.utf8.decode=function(r){return x.decodeUtf8(String.fromCharCode.apply(null,r))};x.text.utf16.encode=function(r,e,t){var n=e;n||(n=new Uint8Array(r.length*2));var i=new Uint16Array(n.buffer);t=t||0;for(var s=t,o=t,a=0;a<r.length;++a)i[o++]=r.charCodeAt(a),s+=2;return e?s-t:n};x.text.utf16.decode=function(r){return String.fromCharCode.apply(null,new Uint16Array(r.buffer))};x.deflate=function(r,e,t){if(e=x.decode64(r.deflate(x.encode64(e)).rval),t){var n=2,i=e.charCodeAt(1);i&32&&(n=6),e=e.substring(n,e.length-4)}return e};x.inflate=function(r,e,t){var n=r.inflate(x.encode64(e)).rval;return n===null?null:x.decode64(n)};var i3=function(r,e,t){if(!r)throw new Error("WebStorage not available.");var n;if(t===null?n=r.removeItem(e):(t=x.encode64(JSON.stringify(t)),n=r.setItem(e,t)),typeof n<"u"&&n.rval!==!0){var i=new Error(n.error.message);throw i.id=n.error.id,i.name=n.error.name,i}},s3=function(r,e){if(!r)throw new Error("WebStorage not available.");var t=r.getItem(e);if(r.init)if(t.rval===null){if(t.error){var n=new Error(t.error.message);throw n.id=t.error.id,n.name=t.error.name,n}t=null}else t=t.rval;return t!==null&&(t=JSON.parse(x.decode64(t))),t},DN=function(r,e,t,n){var i=s3(r,e);i===null&&(i={}),i[t]=n,i3(r,e,i)},CN=function(r,e,t){var n=s3(r,e);return n!==null&&(n=t in n?n[t]:null),n},PN=function(r,e,t){var n=s3(r,e);if(n!==null&&t in n){delete n[t];var i=!0;for(var s in n){i=!1;break}i&&(n=null),i3(r,e,n)}},kN=function(r,e){i3(r,e,null)},wf=function(r,e,t){var n=null;typeof t>"u"&&(t=["web","flash"]);var i,s=!1,o=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),s=i==="flash"}(i==="web"||i==="both")&&(e[0]=localStorage,n=r.apply(this,e),s=!0)}catch(c){o=c}if(s)break}if(!s)throw o;return n};x.setItem=function(r,e,t,n,i){wf(DN,arguments,i)};x.getItem=function(r,e,t,n){return wf(CN,arguments,n)};x.removeItem=function(r,e,t,n){wf(PN,arguments,n)};x.clearItems=function(r,e,t){wf(kN,arguments,t)};x.isEmpty=function(r){for(var e in r)if(r.hasOwnProperty(e))return!1;return!0};x.format=function(r){for(var e=/%./g,t,n,i=0,s=[],o=0;t=e.exec(r);){n=r.substring(o,e.lastIndex-2),n.length>0&&s.push(n),o=e.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i<arguments.length?s.push(arguments[i+++1]):s.push("<?>");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(r.substring(o)),s.join("")};x.formatNumber=function(r,e,t,n){var i=r,s=isNaN(e=Math.abs(e))?2:e,o=t===void 0?",":t,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(s),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)+(s?o+Math.abs(i-u).toFixed(s).slice(2):"")};x.formatSize=function(r){return r>=1073741824?r=x.formatNumber(r/1073741824,2,".","")+" GiB":r>=1048576?r=x.formatNumber(r/1048576,2,".","")+" MiB":r>=1024?r=x.formatNumber(r/1024,0)+" KiB":r=x.formatNumber(r,0)+" bytes",r};x.bytesFromIP=function(r){return r.indexOf(".")!==-1?x.bytesFromIPv4(r):r.indexOf(":")!==-1?x.bytesFromIPv6(r):null};x.bytesFromIPv4=function(r){if(r=r.split("."),r.length!==4)return null;for(var e=x.createBuffer(),t=0;t<r.length;++t){var n=parseInt(r[t],10);if(isNaN(n))return null;e.putByte(n)}return e.getBytes()};x.bytesFromIPv6=function(r){var e=0;r=r.split(":").filter(function(o){return o.length===0&&++e,!0});for(var t=(8-r.length+e)*2,n=x.createBuffer(),i=0;i<8;++i){if(!r[i]||r[i].length===0){n.fillWithByte(0,t),t=0;continue}var s=x.hexToBytes(r[i]);s.length<2&&n.putByte(0),n.putBytes(s)}return n.getBytes()};x.bytesToIP=function(r){return r.length===4?x.bytesToIPv4(r):r.length===16?x.bytesToIPv6(r):null};x.bytesToIPv4=function(r){if(r.length!==4)return null;for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e.join(".")};x.bytesToIPv6=function(r){if(r.length!==16)return null;for(var e=[],t=[],n=0,i=0;i<r.length;i+=2){for(var s=x.bytesToHex(r[i]+r[i+1]);s[0]==="0"&&s!=="0";)s=s.substr(1);if(s==="0"){var o=t[t.length-1],a=e.length;!o||a!==o.end+1?t.push({start:a,end:a}):(o.end=a,o.end-o.start>t[n].end-t[n].start&&(n=t.length-1))}e.push(s)}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(":")};x.estimateCores=function(r,e){if(typeof r=="function"&&(e=r,r={}),r=r||{},"cores"in x&&!r.update)return e(null,x.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return x.cores=navigator.hardwareConcurrency,e(null,x.cores);if(typeof Worker>"u")return x.cores=1,e(null,x.cores);if(typeof Blob>"u")return x.cores=2,e(null,x.cores);var t=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(o){for(var a=Date.now(),c=a+4;Date.now()<c;);self.postMessage({st:a,et:c})})}.toString(),")()"],{type:"application/javascript"}));n([],5,16);function n(o,a,c){if(a===0){var u=Math.floor(o.reduce(function(l,h){return l+h},0)/o.length);return x.cores=Math.max(1,u),URL.revokeObjectURL(t),e(null,x.cores)}i(c,function(l,h){o.push(s(c,h)),n(o,a-1,c)})}function i(o,a){for(var c=[],u=[],l=0;l<o;++l){var h=new Worker(t);h.addEventListener("message",function(f){if(u.push(f.data),u.length===o){for(var d=0;d<o;++d)c[d].terminate();a(null,u)}}),c.push(h)}for(var l=0;l<o;++l)c[l].postMessage(l)}function s(o,a){for(var c=[],u=0;u<o;++u)for(var l=a[u],h=c[u]=[],f=0;f<o;++f)if(u!==f){var d=a[f];(l.st>d.st&&l.st<d.et||d.st>l.st&&d.st<l.et)&&h.push(f)}return c.reduce(function(p,m){return Math.max(p,m.length)},0)}}});var bf=T((Gee,iw)=>{var Fu=rt();Fu.pki=Fu.pki||{};var o3=iw.exports=Fu.pki.oids=Fu.oids=Fu.oids||{};function O(r,e){o3[r]=e,o3[e]=r}function et(r,e){o3[r]=e}O("1.2.840.113549.1.1.1","rsaEncryption");O("1.2.840.113549.1.1.4","md5WithRSAEncryption");O("1.2.840.113549.1.1.5","sha1WithRSAEncryption");O("1.2.840.113549.1.1.7","RSAES-OAEP");O("1.2.840.113549.1.1.8","mgf1");O("1.2.840.113549.1.1.9","pSpecified");O("1.2.840.113549.1.1.10","RSASSA-PSS");O("1.2.840.113549.1.1.11","sha256WithRSAEncryption");O("1.2.840.113549.1.1.12","sha384WithRSAEncryption");O("1.2.840.113549.1.1.13","sha512WithRSAEncryption");O("1.3.101.112","EdDSA25519");O("1.2.840.10040.4.3","dsa-with-sha1");O("1.3.14.3.2.7","desCBC");O("1.3.14.3.2.26","sha1");O("1.3.14.3.2.29","sha1WithRSASignature");O("2.16.840.1.101.3.4.2.1","sha256");O("2.16.840.1.101.3.4.2.2","sha384");O("2.16.840.1.101.3.4.2.3","sha512");O("2.16.840.1.101.3.4.2.4","sha224");O("2.16.840.1.101.3.4.2.5","sha512-224");O("2.16.840.1.101.3.4.2.6","sha512-256");O("1.2.840.113549.2.2","md2");O("1.2.840.113549.2.5","md5");O("1.2.840.113549.1.7.1","data");O("1.2.840.113549.1.7.2","signedData");O("1.2.840.113549.1.7.3","envelopedData");O("1.2.840.113549.1.7.4","signedAndEnvelopedData");O("1.2.840.113549.1.7.5","digestedData");O("1.2.840.113549.1.7.6","encryptedData");O("1.2.840.113549.1.9.1","emailAddress");O("1.2.840.113549.1.9.2","unstructuredName");O("1.2.840.113549.1.9.3","contentType");O("1.2.840.113549.1.9.4","messageDigest");O("1.2.840.113549.1.9.5","signingTime");O("1.2.840.113549.1.9.6","counterSignature");O("1.2.840.113549.1.9.7","challengePassword");O("1.2.840.113549.1.9.8","unstructuredAddress");O("1.2.840.113549.1.9.14","extensionRequest");O("1.2.840.113549.1.9.20","friendlyName");O("1.2.840.113549.1.9.21","localKeyId");O("1.2.840.113549.1.9.22.1","x509Certificate");O("1.2.840.113549.1.12.10.1.1","keyBag");O("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");O("1.2.840.113549.1.12.10.1.3","certBag");O("1.2.840.113549.1.12.10.1.4","crlBag");O("1.2.840.113549.1.12.10.1.5","secretBag");O("1.2.840.113549.1.12.10.1.6","safeContentsBag");O("1.2.840.113549.1.5.13","pkcs5PBES2");O("1.2.840.113549.1.5.12","pkcs5PBKDF2");O("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");O("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");O("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");O("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");O("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");O("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");O("1.2.840.113549.2.7","hmacWithSHA1");O("1.2.840.113549.2.8","hmacWithSHA224");O("1.2.840.113549.2.9","hmacWithSHA256");O("1.2.840.113549.2.10","hmacWithSHA384");O("1.2.840.113549.2.11","hmacWithSHA512");O("1.2.840.113549.3.7","des-EDE3-CBC");O("2.16.840.1.101.3.4.1.2","aes128-CBC");O("2.16.840.1.101.3.4.1.22","aes192-CBC");O("2.16.840.1.101.3.4.1.42","aes256-CBC");O("2.5.4.3","commonName");O("2.5.4.4","surname");O("2.5.4.5","serialNumber");O("2.5.4.6","countryName");O("2.5.4.7","localityName");O("2.5.4.8","stateOrProvinceName");O("2.5.4.9","streetAddress");O("2.5.4.10","organizationName");O("2.5.4.11","organizationalUnitName");O("2.5.4.12","title");O("2.5.4.13","description");O("2.5.4.15","businessCategory");O("2.5.4.17","postalCode");O("2.5.4.42","givenName");O("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");O("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");O("2.16.840.1.113730.1.1","nsCertType");O("2.16.840.1.113730.1.13","nsComment");et("2.5.29.1","authorityKeyIdentifier");et("2.5.29.2","keyAttributes");et("2.5.29.3","certificatePolicies");et("2.5.29.4","keyUsageRestriction");et("2.5.29.5","policyMapping");et("2.5.29.6","subtreesConstraint");et("2.5.29.7","subjectAltName");et("2.5.29.8","issuerAltName");et("2.5.29.9","subjectDirectoryAttributes");et("2.5.29.10","basicConstraints");et("2.5.29.11","nameConstraints");et("2.5.29.12","policyConstraints");et("2.5.29.13","basicConstraints");O("2.5.29.14","subjectKeyIdentifier");O("2.5.29.15","keyUsage");et("2.5.29.16","privateKeyUsagePeriod");O("2.5.29.17","subjectAltName");O("2.5.29.18","issuerAltName");O("2.5.29.19","basicConstraints");et("2.5.29.20","cRLNumber");et("2.5.29.21","cRLReason");et("2.5.29.22","expirationDate");et("2.5.29.23","instructionCode");et("2.5.29.24","invalidityDate");et("2.5.29.25","cRLDistributionPoints");et("2.5.29.26","issuingDistributionPoint");et("2.5.29.27","deltaCRLIndicator");et("2.5.29.28","issuingDistributionPoint");et("2.5.29.29","certificateIssuer");et("2.5.29.30","nameConstraints");O("2.5.29.31","cRLDistributionPoints");O("2.5.29.32","certificatePolicies");et("2.5.29.33","policyMappings");et("2.5.29.34","policyConstraints");O("2.5.29.35","authorityKeyIdentifier");et("2.5.29.36","policyConstraints");O("2.5.29.37","extKeyUsage");et("2.5.29.46","freshestCRL");et("2.5.29.54","inhibitAnyPolicy");O("1.3.6.1.4.1.11129.2.4.2","timestampList");O("1.3.6.1.5.5.7.1.1","authorityInfoAccess");O("1.3.6.1.5.5.7.3.1","serverAuth");O("1.3.6.1.5.5.7.3.2","clientAuth");O("1.3.6.1.5.5.7.3.3","codeSigning");O("1.3.6.1.5.5.7.3.4","emailProtection");O("1.3.6.1.5.5.7.3.8","timeStamping")});var qu=T((Wee,ow)=>{var dt=rt();Ft();bf();var z=ow.exports=dt.asn1=dt.asn1||{};z.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};z.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};z.create=function(r,e,t,n,i){if(dt.util.isArray(n)){for(var s=[],o=0;o<n.length;++o)n[o]!==void 0&&s.push(n[o]);n=s}var a={tagClass:r,type:e,constructed:t,composed:t||dt.util.isArray(n),value:n};return i&&"bitStringContents"in i&&(a.bitStringContents=i.bitStringContents,a.original=z.copy(a)),a};z.copy=function(r,e){var t;if(dt.util.isArray(r)){t=[];for(var n=0;n<r.length;++n)t.push(z.copy(r[n],e));return t}return typeof r=="string"?r:(t={tagClass:r.tagClass,type:r.type,constructed:r.constructed,composed:r.composed,value:z.copy(r.value,e)},e&&!e.excludeBitStringContents&&(t.bitStringContents=r.bitStringContents),t)};z.equals=function(r,e,t){if(dt.util.isArray(r)){if(!dt.util.isArray(e)||r.length!==e.length)return!1;for(var n=0;n<r.length;++n)if(!z.equals(r[n],e[n]))return!1;return!0}if(typeof r!=typeof e)return!1;if(typeof r=="string")return r===e;var i=r.tagClass===e.tagClass&&r.type===e.type&&r.constructed===e.constructed&&r.composed===e.composed&&z.equals(r.value,e.value);return t&&t.includeBitStringContents&&(i=i&&r.bitStringContents===e.bitStringContents),i};z.getBerValueLength=function(r){var e=r.getByte();if(e!==128){var t,n=e&128;return n?t=r.getInt((e&127)<<3):t=e,t}};function Ku(r,e,t){if(t>e){var n=new Error("Too few bytes to parse DER.");throw n.available=r.length(),n.remaining=e,n.requested=t,n}}var NN=function(r,e){var t=r.getByte();if(e--,t!==128){var n,i=t&128;if(!i)n=t;else{var s=t&127;Ku(r,e,s),n=r.getInt(s<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};z.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=dt.util.createBuffer(r));var t=r.length(),n=Ef(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 Ef(r,e,t,n){var i;Ku(r,e,2);var s=r.getByte();e--;var o=s&192,a=s&31;i=r.length();var c=NN(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,h,f=(s&32)===32;if(f)if(l=[],c===void 0)for(;;){if(Ku(r,e,2),r.bytes(2)===String.fromCharCode(0,0)){r.getBytes(2),e-=2;break}i=r.length(),l.push(Ef(r,e,t+1,n)),e-=i-r.length()}else for(;c>0;)i=r.length(),l.push(Ef(r,c,t+1,n)),e-=i-r.length(),c-=i-r.length();if(l===void 0&&o===z.Class.UNIVERSAL&&a===z.Type.BITSTRING&&(h=r.bytes(c)),l===void 0&&n.decodeBitStrings&&o===z.Class.UNIVERSAL&&a===z.Type.BITSTRING&&c>1){var d=r.read,p=e,m=0;if(a===z.Type.BITSTRING&&(Ku(r,e,1),m=r.getByte(),e--),m===0)try{i=r.length();var g={strict:!0,decodeBitStrings:!0},y=Ef(r,e,t+1,g),b=i-r.length();e-=b,a==z.Type.BITSTRING&&b++;var E=y.tagClass;b===c&&(E===z.Class.UNIVERSAL||E===z.Class.CONTEXT_SPECIFIC)&&(l=[y])}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===z.Type.BMPSTRING)for(l="";c>0;c-=2)Ku(r,e,2),l+=String.fromCharCode(r.getInt16()),e-=2;else l=r.getBytes(c),e-=c}var R=h===void 0?null:{bitStringContents:h};return z.create(o,a,f,l,R)}z.toDer=function(r){var e=dt.util.createBuffer(),t=r.tagClass|r.type,n=dt.util.createBuffer(),i=!1;if("bitStringContents"in r&&(i=!0,r.original&&(i=z.equals(r,r.original))),i)n.putBytes(r.bitStringContents);else if(r.composed){r.constructed?t|=32:n.putByte(0);for(var s=0;s<r.value.length;++s)r.value[s]!==void 0&&n.putBuffer(z.toDer(r.value[s]))}else if(r.type===z.Type.BMPSTRING)for(var s=0;s<r.value.length;++s)n.putInt16(r.value.charCodeAt(s));else r.type===z.Type.INTEGER&&r.value.length>1&&(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 o=n.length(),a="";do a+=String.fromCharCode(o&255),o=o>>>8;while(o>0);e.putByte(a.length|128);for(var s=a.length-1;s>=0;--s)e.putByte(a.charCodeAt(s))}return e.putBuffer(n),e};z.oidToDer=function(r){var e=r.split("."),t=dt.util.createBuffer();t.putByte(40*parseInt(e[0],10)+parseInt(e[1],10));for(var n,i,s,o,a=2;a<e.length;++a){n=!0,i=[],s=parseInt(e[a],10);do o=s&127,s=s>>>7,n||(o|=128),i.push(o),n=!1;while(s>0);for(var c=i.length-1;c>=0;--c)t.putByte(i[c])}return t};z.derToOid=function(r){var e;typeof r=="string"&&(r=dt.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};z.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),s=parseInt(r.substr(6,2),10),o=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(s,o,a,0),u&&(c=r.charAt(u),c==="+"||c==="-")){var l=parseInt(r.substr(u+1,2),10),h=parseInt(r.substr(u+4,2),10),f=l*60+h;f*=6e4,c==="+"?e.setTime(+e-f):e.setTime(+e+f)}return e};z.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),s=parseInt(r.substr(8,2),10),o=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 h=r.length-5,f=r.charAt(h);if(f==="+"||f==="-"){var d=parseInt(r.substr(h+1,2),10),p=parseInt(r.substr(h+4,2),10);u=d*60+p,u*=6e4,f==="+"&&(u*=-1),l=!0}return r.charAt(14)==="."&&(c=parseFloat(r.substr(14),10)*1e3),l?(e.setUTCFullYear(t,n,i),e.setUTCHours(s,o,a,c),e.setTime(+e+u)):(e.setFullYear(t,n,i),e.setHours(s,o,a,c)),e};z.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<t.length;++n)t[n].length<2&&(e+="0"),e+=t[n];return e+="Z",e};z.dateToGeneralizedTime=function(r){if(typeof r=="string")return r;var e="",t=[];t.push(""+r.getUTCFullYear()),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<t.length;++n)t[n].length<2&&(e+="0"),e+=t[n];return e+="Z",e};z.integerToDer=function(r){var e=dt.util.createBuffer();if(r>=-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};z.derToInteger=function(r){typeof r=="string"&&(r=dt.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)};z.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&&dt.util.isArray(e.value))for(var s=0,o=0;i&&o<e.value.length;++o)i=e.value[o].optional||!1,r.value[s]&&(i=z.validate(r.value[s],e.value[o],t,n),i?++s:e.value[o].optional&&(i=!0)),!i&&n&&n.push("["+e.name+'] Tag class "'+e.tagClass+'", type "'+e.type+'" expected value length "'+e.value.length+'", got "'+r.value.length+'"');if(i&&t&&(e.capture&&(t[e.capture]=r.value),e.captureAsn1&&(t[e.captureAsn1]=r),e.captureBitStringContents&&"bitStringContents"in r&&(t[e.captureBitStringContents]=r.bitStringContents),e.captureBitStringValue&&"bitStringContents"in r)){var a;if(r.bitStringContents.length<2)t[e.captureBitStringValue]="";else{var c=r.bitStringContents.charCodeAt(0);if(c!==0)throw new Error("captureBitStringValue only supported for zero unused bits");t[e.captureBitStringValue]=r.bitStringContents.slice(1)}}}else n&&n.push("["+e.name+'] Expected constructed "'+e.constructed+'", got "'+r.constructed+'"');else n&&(r.tagClass!==e.tagClass&&n.push("["+e.name+'] Expected tag class "'+e.tagClass+'", got "'+r.tagClass+'"'),r.type!==e.type&&n.push("["+e.name+'] Expected type "'+e.type+'", got "'+r.type+'"'));return i};var sw=/[^\\u0000-\\u00ff]/;z.prettyPrint=function(r,e,t){var n="";e=e||0,t=t||2,e>0&&(n+=`
|
|
6
|
+
`);for(var i="",s=0;s<e*t;++s)i+=" ";switch(n+=i+"Tag: ",r.tagClass){case z.Class.UNIVERSAL:n+="Universal:";break;case z.Class.APPLICATION:n+="Application:";break;case z.Class.CONTEXT_SPECIFIC:n+="Context-Specific:";break;case z.Class.PRIVATE:n+="Private:";break}if(r.tagClass===z.Class.UNIVERSAL)switch(n+=r.type,r.type){case z.Type.NONE:n+=" (None)";break;case z.Type.BOOLEAN:n+=" (Boolean)";break;case z.Type.INTEGER:n+=" (Integer)";break;case z.Type.BITSTRING:n+=" (Bit string)";break;case z.Type.OCTETSTRING:n+=" (Octet string)";break;case z.Type.NULL:n+=" (Null)";break;case z.Type.OID:n+=" (Object Identifier)";break;case z.Type.ODESC:n+=" (Object Descriptor)";break;case z.Type.EXTERNAL:n+=" (External or Instance of)";break;case z.Type.REAL:n+=" (Real)";break;case z.Type.ENUMERATED:n+=" (Enumerated)";break;case z.Type.EMBEDDED:n+=" (Embedded PDV)";break;case z.Type.UTF8:n+=" (UTF8)";break;case z.Type.ROID:n+=" (Relative Object Identifier)";break;case z.Type.SEQUENCE:n+=" (Sequence)";break;case z.Type.SET:n+=" (Set)";break;case z.Type.PRINTABLESTRING:n+=" (Printable String)";break;case z.Type.IA5String:n+=" (IA5String (ASCII))";break;case z.Type.UTCTIME:n+=" (UTC time)";break;case z.Type.GENERALIZEDTIME:n+=" (Generalized time)";break;case z.Type.BMPSTRING:n+=" (BMP String)";break}else n+=r.type;if(n+=`
|
|
7
|
+
`,n+=i+"Constructed: "+r.constructed+`
|
|
8
|
+
`,r.composed){for(var o=0,a="",s=0;s<r.value.length;++s)r.value[s]!==void 0&&(o+=1,a+=z.prettyPrint(r.value[s],e+1,t),s+1<r.value.length&&(a+=","));n+=i+"Sub values: "+o+a}else{if(n+=i+"Value: ",r.type===z.Type.OID){var c=z.derToOid(r.value);n+=c,dt.pki&&dt.pki.oids&&c in dt.pki.oids&&(n+=" ("+dt.pki.oids[c]+") ")}if(r.type===z.Type.INTEGER)try{n+=z.derToInteger(r.value)}catch{n+="0x"+dt.util.bytesToHex(r.value)}else if(r.type===z.Type.BITSTRING){if(r.value.length>1?n+="0x"+dt.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===z.Type.OCTETSTRING)sw.test(r.value)||(n+="("+r.value+") "),n+="0x"+dt.util.bytesToHex(r.value);else if(r.type===z.Type.UTF8)try{n+=dt.util.decodeUtf8(r.value)}catch(l){if(l.message==="URI malformed")n+="0x"+dt.util.bytesToHex(r.value)+" (malformed UTF8)";else throw l}else r.type===z.Type.PRINTABLESTRING||r.type===z.Type.IA5String?n+=r.value:sw.test(r.value)?n+="0x"+dt.util.bytesToHex(r.value):r.value.length===0?n+="[null]":n+=r.value}return n}});var c3=T((Yee,aw)=>{var rr=rt();Ft();aw.exports=rr.cipher=rr.cipher||{};rr.cipher.algorithms=rr.cipher.algorithms||{};rr.cipher.createCipher=function(r,e){var t=r;if(typeof t=="string"&&(t=rr.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new rr.cipher.BlockCipher({algorithm:t,key:e,decrypt:!1})};rr.cipher.createDecipher=function(r,e){var t=r;if(typeof t=="string"&&(t=rr.cipher.getAlgorithm(t),t&&(t=t())),!t)throw new Error("Unsupported algorithm: "+r);return new rr.cipher.BlockCipher({algorithm:t,key:e,decrypt:!0})};rr.cipher.registerAlgorithm=function(r,e){r=r.toUpperCase(),rr.cipher.algorithms[r]=e};rr.cipher.getAlgorithm=function(r){return r=r.toUpperCase(),r in rr.cipher.algorithms?rr.cipher.algorithms[r]:null};var a3=rr.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)};a3.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=rr.util.createBuffer(),this.output=r.output||rr.util.createBuffer(),this.mode.start(e)};a3.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()};a3.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 l3=T((Qee,cw)=>{var nr=rt();Ft();nr.cipher=nr.cipher||{};var xe=cw.exports=nr.cipher.modes=nr.cipher.modes||{};xe.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)};xe.ecb.prototype.start=function(r){};xe.ecb.prototype.encrypt=function(r,e,t){if(r.length()<this.blockSize&&!(t&&r.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=r.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)e.putInt32(this._outBlock[n])};xe.ecb.prototype.decrypt=function(r,e,t){if(r.length()<this.blockSize&&!(t&&r.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=r.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)e.putInt32(this._outBlock[n])};xe.ecb.prototype.pad=function(r,e){var t=r.length()===this.blockSize?this.blockSize:this.blockSize-r.length();return r.fillWithByte(t,t),!0};xe.ecb.prototype.unpad=function(r,e){if(e.overflow>0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};xe.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)};xe.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=vf(r.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};xe.cbc.prototype.encrypt=function(r,e,t){if(r.length()<this.blockSize&&!(t&&r.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=this._prev[n]^r.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)e.putInt32(this._outBlock[n]);this._prev=this._outBlock};xe.cbc.prototype.decrypt=function(r,e,t){if(r.length()<this.blockSize&&!(t&&r.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=r.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)e.putInt32(this._prev[n]^this._outBlock[n]);this._prev=this._inBlock.slice(0)};xe.cbc.prototype.pad=function(r,e){var t=r.length()===this.blockSize?this.blockSize:this.blockSize-r.length();return r.fillWithByte(t,t),!0};xe.cbc.prototype.unpad=function(r,e){if(e.overflow>0)return!1;var t=r.length(),n=r.at(t-1);return n>this.blockSize<<2?!1:(r.truncate(n),!0)};xe.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=nr.util.createBuffer(),this._partialBytes=0};xe.cfb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=vf(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};xe.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;i<this._ints;++i)this._inBlock[i]=r.getInt32()^this._outBlock[i],e.putInt32(this._inBlock[i]);return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=r.getInt32()^this._outBlock[i],this._partialOutput.putInt32(this._partialBlock[i]);if(s>0)r.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};xe.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;i<this._ints;++i)this._inBlock[i]=r.getInt32(),e.putInt32(this._inBlock[i]^this._outBlock[i]);return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=r.getInt32(),this._partialOutput.putInt32(this._partialBlock[i]^this._outBlock[i]);if(s>0)r.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};xe.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=nr.util.createBuffer(),this._partialBytes=0};xe.ofb.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=vf(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};xe.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;i<this._ints;++i)e.putInt32(r.getInt32()^this._outBlock[i]),this._inBlock[i]=this._outBlock[i];return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(r.getInt32()^this._outBlock[i]);if(s>0)r.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._outBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};xe.ofb.prototype.decrypt=xe.ofb.prototype.encrypt;xe.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=nr.util.createBuffer(),this._partialBytes=0};xe.ctr.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");this._iv=vf(r.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};xe.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;i<this._ints;++i)e.putInt32(r.getInt32()^this._outBlock[i]);else{var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(r.getInt32()^this._outBlock[i]);if(s>0&&(r.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}xf(this._inBlock)};xe.ctr.prototype.decrypt=xe.ctr.prototype.encrypt;xe.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=nr.util.createBuffer(),this._partialBytes=0,this._R=3774873600};xe.gcm.prototype.start=function(r){if(!("iv"in r))throw new Error("Invalid IV parameter.");var e=nr.util.createBuffer(r.iv);this._cipherLength=0;var t;if("additionalData"in r?t=nr.util.createBuffer(r.additionalData):t=nr.util.createBuffer(),"tagLength"in r?this._tagLength=r.tagLength:this._tagLength=128,this._tag=null,r.decrypt&&(this._tag=nr.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(u3(n*8)))}this._inBlock=this._j0.slice(0),xf(this._inBlock),this._partialBytes=0,t=nr.util.createBuffer(t),this._aDataLength=u3(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()])};xe.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;i<this._ints;++i)e.putInt32(this._outBlock[i]^=r.getInt32());this._cipherLength+=this.blockSize}else{var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(r.getInt32()^this._outBlock[i]);if(s<=0||t){if(t){var o=n%this.blockSize;this._cipherLength+=o,this._partialOutput.truncate(this.blockSize-o)}else this._cipherLength+=this.blockSize;for(var i=0;i<this._ints;++i)this._outBlock[i]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!t)return r.read-=this.blockSize,e.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;e.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),xf(this._inBlock)};xe.gcm.prototype.decrypt=function(r,e,t){var n=r.length();if(n<this.blockSize&&!(t&&n>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),xf(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;i<this._ints;++i)e.putInt32(this._outBlock[i]^this._hashBlock[i]);n<this.blockSize?this._cipherLength+=n%this.blockSize:this._cipherLength+=this.blockSize};xe.gcm.prototype.afterFinish=function(r,e){var t=!0;e.decrypt&&e.overflow&&r.truncate(this.blockSize-e.overflow),this.tag=nr.util.createBuffer();var n=this._aDataLength.concat(u3(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,n);var i=[];this.cipher.encrypt(this._j0,i);for(var s=0;s<this._ints;++s)this.tag.putInt32(this._s[s]^i[s]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),e.decrypt&&this.tag.bytes()!==this._tag&&(t=!1),t};xe.gcm.prototype.multiply=function(r,e){for(var t=[0,0,0,0],n=e.slice(0),i=0;i<128;++i){var s=r[i/32|0]&1<<31-i%32;s&&(t[0]^=n[0],t[1]^=n[1],t[2]^=n[2],t[3]^=n[3]),this.pow(n,n)}return t};xe.gcm.prototype.pow=function(r,e){for(var t=r[3]&1,n=3;n>0;--n)e[n]=r[n]>>>1|(r[n-1]&1)<<31;e[0]=r[0]>>>1,t&&(e[0]^=this._R)};xe.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,s=this._m[t][i];e[0]^=s[0],e[1]^=s[1],e[2]^=s[2],e[3]^=s[3]}return e};xe.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)};xe.gcm.prototype.generateHashTable=function(r,e){for(var t=8/e,n=4*t,i=16*t,s=new Array(i),o=0;o<i;++o){var a=[0,0,0,0],c=o/n|0,u=(n-1-o%n)*e;a[c]=1<<e-1<<u,s[o]=this.generateSubHashTable(this.multiply(a,r),e)}return s};xe.gcm.prototype.generateSubHashTable=function(r,e){var t=1<<e,n=t>>>1,i=new Array(t);i[n]=r.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s<n;){for(var o=1;o<s;++o){var a=i[s],c=i[o];i[s+o]=[a[0]^c[0],a[1]^c[1],a[2]^c[2],a[3]^c[3]]}s*=2}for(i[0]=[0,0,0,0],s=n+1;s<t;++s){var u=i[s^n];i[s]=[r[0]^u[0],r[1]^u[1],r[2]^u[2],r[3]^u[3]]}return i};function vf(r,e){if(typeof r=="string"&&(r=nr.util.createBuffer(r)),nr.util.isArray(r)&&r.length>4){var t=r;r=nr.util.createBuffer();for(var n=0;n<t.length;++n)r.putByte(t[n])}if(r.length()<e)throw new Error("Invalid IV length; got "+r.length()+" bytes and expected "+e+" bytes.");if(!nr.util.isArray(r)){for(var i=[],s=e/4,n=0;n<s;++n)i.push(r.getInt32());r=i}return r}function xf(r){r[r.length-1]=r[r.length-1]+1&4294967295}function u3(r){return[r/4294967296|0,r&4294967295]}});var Sf=T((Xee,fw)=>{var ht=rt();c3();l3();Ft();fw.exports=ht.aes=ht.aes||{};ht.aes.startEncrypting=function(r,e,t,n){var i=_f({key:r,output:t,decrypt:!1,mode:n});return i.start(e),i};ht.aes.createEncryptionCipher=function(r,e){return _f({key:r,output:null,decrypt:!1,mode:e})};ht.aes.startDecrypting=function(r,e,t,n){var i=_f({key:r,output:t,decrypt:!0,mode:n});return i.start(e),i};ht.aes.createDecryptionCipher=function(r,e){return _f({key:r,output:null,decrypt:!0,mode:e})};ht.aes.Algorithm=function(r,e){d3||lw();var t=this;t.name=r,t.mode=new e({blockSize:16,cipher:{encrypt:function(n,i){return f3(t._w,n,i,!1)},decrypt:function(n,i){return f3(t._w,n,i,!0)}}}),t._init=!1};ht.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=ht.util.createBuffer(e);else if(ht.util.isArray(e)&&(e.length===16||e.length===24||e.length===32)){t=e,e=ht.util.createBuffer();for(var n=0;n<t.length;++n)e.putByte(t[n])}if(!ht.util.isArray(e)){t=e,e=[];var i=t.length();if(i===16||i===24||i===32){i=i>>>2;for(var n=0;n<i;++n)e.push(t.getInt32())}}if(!ht.util.isArray(e)||!(e.length===4||e.length===6||e.length===8))throw new Error("Invalid key parameter.");var s=this.mode.name,o=["CFB","OFB","CTR","GCM"].indexOf(s)!==-1;this._w=hw(e,r.decrypt&&!o),this._init=!0}};ht.aes._expandKey=function(r,e){return d3||lw(),hw(r,e)};ht.aes._updateBlock=f3;Oa("AES-ECB",ht.cipher.modes.ecb);Oa("AES-CBC",ht.cipher.modes.cbc);Oa("AES-CFB",ht.cipher.modes.cfb);Oa("AES-OFB",ht.cipher.modes.ofb);Oa("AES-CTR",ht.cipher.modes.ctr);Oa("AES-GCM",ht.cipher.modes.gcm);function Oa(r,e){var t=function(){return new ht.aes.Algorithm(r,e)};ht.cipher.registerAlgorithm(r,t)}var d3=!1,La=4,Cr,h3,uw,Do,Wn;function lw(){d3=!0,uw=[0,1,2,4,8,16,32,64,128,27,54];for(var r=new Array(256),e=0;e<128;++e)r[e]=e<<1,r[e+128]=e+128<<1^283;Cr=new Array(256),h3=new Array(256),Do=new Array(4),Wn=new Array(4);for(var e=0;e<4;++e)Do[e]=new Array(256),Wn[e]=new Array(256);for(var t=0,n=0,i,s,o,a,c,u,l,e=0;e<256;++e){a=n^n<<1^n<<2^n<<3^n<<4,a=a>>8^a&255^99,Cr[t]=a,h3[a]=t,c=r[a],i=r[t],s=r[i],o=r[s],u=c<<24^a<<16^a<<8^(a^c),l=(i^s^o)<<24^(t^o)<<16^(t^s^o)<<8^(t^i^o);for(var h=0;h<4;++h)Do[h][t]=u,Wn[h][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;t===0?t=n=1:(t=i^r[r[r[i^o]]],n^=r[r[n]])}}function hw(r,e){for(var t=r.slice(0),n,i=1,s=t.length,o=s+6+1,a=La*o,c=s;c<a;++c)n=t[c-1],c%s===0?(n=Cr[n>>>16&255]<<24^Cr[n>>>8&255]<<16^Cr[n&255]<<8^Cr[n>>>24]^uw[i]<<24,i++):s>6&&c%s===4&&(n=Cr[n>>>24]<<24^Cr[n>>>16&255]<<16^Cr[n>>>8&255]<<8^Cr[n&255]),t[c]=t[c-s]^n;if(e){var u,l=Wn[0],h=Wn[1],f=Wn[2],d=Wn[3],p=t.slice(0);a=t.length;for(var c=0,m=a-La;c<a;c+=La,m-=La)if(c===0||c===a-La)p[c]=t[m],p[c+1]=t[m+3],p[c+2]=t[m+2],p[c+3]=t[m+1];else for(var g=0;g<La;++g)u=t[m+g],p[c+(3&-g)]=l[Cr[u>>>24]]^h[Cr[u>>>16&255]]^f[Cr[u>>>8&255]]^d[Cr[u&255]];t=p}return t}function f3(r,e,t,n){var i=r.length/4-1,s,o,a,c,u;n?(s=Wn[0],o=Wn[1],a=Wn[2],c=Wn[3],u=h3):(s=Do[0],o=Do[1],a=Do[2],c=Do[3],u=Cr);var l,h,f,d,p,m,g;l=e[0]^r[0],h=e[n?3:1]^r[1],f=e[2]^r[2],d=e[n?1:3]^r[3];for(var y=3,b=1;b<i;++b)p=s[l>>>24]^o[h>>>16&255]^a[f>>>8&255]^c[d&255]^r[++y],m=s[h>>>24]^o[f>>>16&255]^a[d>>>8&255]^c[l&255]^r[++y],g=s[f>>>24]^o[d>>>16&255]^a[l>>>8&255]^c[h&255]^r[++y],d=s[d>>>24]^o[l>>>16&255]^a[h>>>8&255]^c[f&255]^r[++y],l=p,h=m,f=g;t[0]=u[l>>>24]<<24^u[h>>>16&255]<<16^u[f>>>8&255]<<8^u[d&255]^r[++y],t[n?3:1]=u[h>>>24]<<24^u[f>>>16&255]<<16^u[d>>>8&255]<<8^u[l&255]^r[++y],t[2]=u[f>>>24]<<24^u[d>>>16&255]<<16^u[l>>>8&255]<<8^u[h&255]^r[++y],t[n?1:3]=u[d>>>24]<<24^u[l>>>16&255]<<16^u[h>>>8&255]<<8^u[f&255]^r[++y]}function _f(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="AES-"+e,n;r.decrypt?n=ht.cipher.createDecipher(t,r.key):n=ht.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof ht.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var mw=T((jee,pw)=>{var xt=rt();c3();l3();Ft();pw.exports=xt.des=xt.des||{};xt.des.startEncrypting=function(r,e,t,n){var i=Af({key:r,output:t,decrypt:!1,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};xt.des.createEncryptionCipher=function(r,e){return Af({key:r,output:null,decrypt:!1,mode:e})};xt.des.startDecrypting=function(r,e,t,n){var i=Af({key:r,output:t,decrypt:!0,mode:n||(e===null?"ECB":"CBC")});return i.start(e),i};xt.des.createDecryptionCipher=function(r,e){return Af({key:r,output:null,decrypt:!0,mode:e})};xt.des.Algorithm=function(r,e){var t=this;t.name=r,t.mode=new e({blockSize:8,cipher:{encrypt:function(n,i){return dw(t._keys,n,i,!1)},decrypt:function(n,i){return dw(t._keys,n,i,!0)}}}),t._init=!1};xt.des.Algorithm.prototype.initialize=function(r){if(!this._init){var e=xt.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=VN(e),this._init=!0}};bi("DES-ECB",xt.cipher.modes.ecb);bi("DES-CBC",xt.cipher.modes.cbc);bi("DES-CFB",xt.cipher.modes.cfb);bi("DES-OFB",xt.cipher.modes.ofb);bi("DES-CTR",xt.cipher.modes.ctr);bi("3DES-ECB",xt.cipher.modes.ecb);bi("3DES-CBC",xt.cipher.modes.cbc);bi("3DES-CFB",xt.cipher.modes.cfb);bi("3DES-OFB",xt.cipher.modes.ofb);bi("3DES-CTR",xt.cipher.modes.ctr);function bi(r,e){var t=function(){return new xt.des.Algorithm(r,e)};xt.cipher.registerAlgorithm(r,t)}var LN=[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],ON=[-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],BN=[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],MN=[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],UN=[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],FN=[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],KN=[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],qN=[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 VN(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],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[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],h=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[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],m=r.length()>8?3:1,g=[],y=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],b=0,E,R=0;R<m;R++){var v=r.getInt32(),_=r.getInt32();E=(v>>>4^_)&252645135,_^=E,v^=E<<4,E=(_>>>-16^v)&65535,v^=E,_^=E<<-16,E=(v>>>2^_)&858993459,_^=E,v^=E<<2,E=(_>>>-16^v)&65535,v^=E,_^=E<<-16,E=(v>>>1^_)&1431655765,_^=E,v^=E<<1,E=(_>>>8^v)&16711935,v^=E,_^=E<<8,E=(v>>>1^_)&1431655765,_^=E,v^=E<<1,E=v<<8|_>>>20&240,v=_<<24|_<<8&16711680|_>>>8&65280|_>>>24&240,_=E;for(var I=0;I<y.length;++I){y[I]?(v=v<<2|v>>>26,_=_<<2|_>>>26):(v=v<<1|v>>>27,_=_<<1|_>>>27),v&=-15,_&=-15;var P=e[v>>>28]|t[v>>>24&15]|n[v>>>20&15]|i[v>>>16&15]|s[v>>>12&15]|o[v>>>8&15]|a[v>>>4&15],M=c[_>>>28]|u[_>>>24&15]|l[_>>>20&15]|h[_>>>16&15]|f[_>>>12&15]|d[_>>>8&15]|p[_>>>4&15];E=(M>>>16^P)&65535,g[b++]=P^E,g[b++]=M^E<<16}}return g}function dw(r,e,t,n){var i=r.length===32?3:9,s;i===3?s=n?[30,-2,-2]:[0,32,2]:s=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var o,a=e[0],c=e[1];o=(a>>>4^c)&252645135,c^=o,a^=o<<4,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u<i;u+=3){for(var l=s[u+1],h=s[u+2],f=s[u];f!=l;f+=h){var d=c^r[f],p=(c>>>4|c<<28)^r[f+1];o=a,a=c,c=o^(ON[d>>>24&63]|MN[d>>>16&63]|FN[d>>>8&63]|qN[d&63]|LN[p>>>24&63]|BN[p>>>16&63]|UN[p>>>8&63]|KN[p&63])}o=a,a=c,c=o}a=a>>>1|a<<31,c=c>>>1|c<<31,o=(a>>>1^c)&1431655765,c^=o,a^=o<<1,o=(c>>>8^a)&16711935,a^=o,c^=o<<8,o=(c>>>2^a)&858993459,a^=o,c^=o<<2,o=(a>>>16^c)&65535,c^=o,a^=o<<16,o=(a>>>4^c)&252645135,c^=o,a^=o<<4,t[0]=a,t[1]=c}function Af(r){r=r||{};var e=(r.mode||"CBC").toUpperCase(),t="DES-"+e,n;r.decrypt?n=xt.cipher.createDecipher(t,r.key):n=xt.cipher.createCipher(t,r.key);var i=n.start;return n.start=function(s,o){var a=null;o instanceof xt.util.ByteBuffer&&(a=o,o={}),o=o||{},o.output=a,o.iv=s,i.call(n,o)},n}});var Co=T((Zee,gw)=>{var Rf=rt();gw.exports=Rf.md=Rf.md||{};Rf.md.algorithms=Rf.md.algorithms||{}});var ww=T((Jee,yw)=>{var Qi=rt();Co();Ft();var zN=yw.exports=Qi.hmac=Qi.hmac||{};zN.create=function(){var r=null,e=null,t=null,n=null,i={};return i.start=function(s,o){if(s!==null)if(typeof s=="string")if(s=s.toLowerCase(),s in Qi.md.algorithms)e=Qi.md.algorithms[s].create();else throw new Error('Unknown hash algorithm "'+s+'"');else e=s;if(o===null)o=r;else{if(typeof o=="string")o=Qi.util.createBuffer(o);else if(Qi.util.isArray(o)){var a=o;o=Qi.util.createBuffer();for(var c=0;c<a.length;++c)o.putByte(a[c])}var u=o.length();u>e.blockLength&&(e.start(),e.update(o.bytes()),o=e.digest()),t=Qi.util.createBuffer(),n=Qi.util.createBuffer(),u=o.length();for(var c=0;c<u;++c){var a=o.at(c);t.putByte(54^a),n.putByte(92^a)}if(u<e.blockLength)for(var a=e.blockLength-u,c=0;c<a;++c)t.putByte(54),n.putByte(92);r=o,t=t.bytes(),n=n.bytes()}e.start(),e.update(t)},i.update=function(s){e.update(s)},i.getMac=function(){var s=e.digest().bytes();return e.start(),e.update(n),e.update(s),e.digest()},i.digest=i.getMac,i}});var Ns=T(()=>{});var p3=T((rte,bw)=>{var Pr=rt();ww();Co();Ft();var HN=Pr.pkcs5=Pr.pkcs5||{},Xi;Pr.util.isNodejs&&!Pr.options.usePureJavaScript&&(Xi=Ns());bw.exports=Pr.pbkdf2=HN.pbkdf2=function(r,e,t,n,i,s){if(typeof i=="function"&&(s=i,i=null),Pr.util.isNodejs&&!Pr.options.usePureJavaScript&&Xi.pbkdf2&&(i===null||typeof i!="object")&&(Xi.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),r=Buffer.from(r,"binary"),e=Buffer.from(e,"binary"),s?Xi.pbkdf2Sync.length===4?Xi.pbkdf2(r,e,t,n,function(E,R){if(E)return s(E);s(null,R.toString("binary"))}):Xi.pbkdf2(r,e,t,n,i,function(E,R){if(E)return s(E);s(null,R.toString("binary"))}):Xi.pbkdf2Sync.length===4?Xi.pbkdf2Sync(r,e,t,n).toString("binary"):Xi.pbkdf2Sync(r,e,t,n,i).toString("binary");if((typeof i>"u"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in Pr.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=Pr.md[i].create()}var o=i.digestLength;if(n>4294967295*o){var a=new Error("Derived key is too long.");if(s)return s(a);throw a}var c=Math.ceil(n/o),u=n-(c-1)*o,l=Pr.hmac.create();l.start(i,r);var h="",f,d,p;if(!s){for(var m=1;m<=c;++m){l.start(null,null),l.update(e),l.update(Pr.util.int32ToBytes(m)),f=p=l.digest().getBytes();for(var g=2;g<=t;++g)l.start(null,null),l.update(p),d=l.digest().getBytes(),f=Pr.util.xorBytes(f,d,o),p=d;h+=m<c?f:f.substr(0,u)}return h}var m=1,g;function y(){if(m>c)return s(null,h);l.start(null,null),l.update(e),l.update(Pr.util.int32ToBytes(m)),f=p=l.digest().getBytes(),g=2,b()}function b(){if(g<=t)return l.start(null,null),l.update(p),d=l.digest().getBytes(),f=Pr.util.xorBytes(f,d,o),p=d,++g,Pr.util.setImmediate(b);h+=m<c?f:f.substr(0,u),++m,y()}y()}});var xw=T((nte,vw)=>{var Tf=rt();Ft();var Ew=vw.exports=Tf.pem=Tf.pem||{};Ew.encode=function(r,e){e=e||{};var t="-----BEGIN "+r.type+`-----\r
|
|
9
|
+
`,n;if(r.procType&&(n={name:"Proc-Type",values:[String(r.procType.version),r.procType.type]},t+=If(n)),r.contentDomain&&(n={name:"Content-Domain",values:[r.contentDomain]},t+=If(n)),r.dekInfo&&(n={name:"DEK-Info",values:[r.dekInfo.algorithm]},r.dekInfo.parameters&&n.values.push(r.dekInfo.parameters),t+=If(n)),r.headers)for(var i=0;i<r.headers.length;++i)t+=If(r.headers[i]);return r.procType&&(t+=`\r
|
|
10
|
+
`),t+=Tf.util.encode64(r.body,e.maxline||64)+`\r
|
|
11
|
+
`,t+="-----END "+r.type+`-----\r
|
|
12
|
+
`,t};Ew.decode=function(r){for(var e=[],t=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,n=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,s;s=t.exec(r),!!s;){var o=s[1];o==="NEW CERTIFICATE REQUEST"&&(o="CERTIFICATE REQUEST");var a={type:o,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Tf.util.decode64(s[3])};if(e.push(a),!!s[2]){for(var c=s[2].split(i),u=0;s&&u<c.length;){for(var l=c[u].replace(/\s+$/,""),h=u+1;h<c.length;++h){var f=c[h];if(!/\s/.test(f[0]))break;l+=f,u=h}if(s=l.match(n),s){for(var d={name:s[1],values:[]},p=s[2].split(","),m=0;m<p.length;++m)d.values.push($N(p[m]));if(a.procType)if(!a.contentDomain&&d.name==="Content-Domain")a.contentDomain=p[0]||"";else if(!a.dekInfo&&d.name==="DEK-Info"){if(d.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');a.dekInfo={algorithm:p[0],parameters:p[1]||null}}else a.headers.push(d);else{if(d.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(d.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');a.procType={version:p[0],type:p[1]}}}++u}if(a.procType==="ENCRYPTED"&&!a.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(e.length===0)throw new Error("Invalid PEM formatted message.");return e};function If(r){for(var e=r.name+": ",t=[],n=function(c,u){return" "+u},i=0;i<r.values.length;++i)t.push(r.values[i].replace(/^(\S+\r\n)/,n));e+=t.join(",")+`\r
|
|
13
|
+
`;for(var s=0,o=-1,i=0;i<e.length;++i,++s)if(s>65&&o!==-1){var a=e[o];a===","?(++o,e=e.substr(0,o)+`\r
|
|
14
|
+
`+e.substr(o)):e=e.substr(0,o)+`\r
|
|
15
|
+
`+a+e.substr(o+1),s=i-o-1,o=-1,++i}else(e[i]===" "||e[i]===" "||e[i]===",")&&(o=i);return e}function $N(r){return r.replace(/^\s+/,"")}});var Tw=T((ite,Iw)=>{var Ei=rt();Co();Ft();var Sw=Iw.exports=Ei.sha256=Ei.sha256||{};Ei.md.sha256=Ei.md.algorithms.sha256=Sw;Sw.create=function(){Aw||GN();var r=null,e=Ei.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,s=0;s<i;++s)n.fullMessageLength.push(0);return e=Ei.util.createBuffer(),r={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=Ei.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),_w(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=Ei.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(m3.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var h={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4,h5:r.h5,h6:r.h6,h7:r.h7};_w(h,t,i);var f=Ei.util.createBuffer();return f.putInt32(h.h0),f.putInt32(h.h1),f.putInt32(h.h2),f.putInt32(h.h3),f.putInt32(h.h4),f.putInt32(h.h5),f.putInt32(h.h6),f.putInt32(h.h7),f},n};var m3=null,Aw=!1,Rw=null;function GN(){m3=String.fromCharCode(128),m3+=Ei.util.fillString(String.fromCharCode(0),64),Rw=[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],Aw=!0}function _w(r,e,t){for(var n,i,s,o,a,c,u,l,h,f,d,p,m,g,y,b=t.length();b>=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,h=r.h1,f=r.h2,d=r.h3,p=r.h4,m=r.h5,g=r.h6,y=r.h7,u=0;u<64;++u)o=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),a=g^p&(m^g),s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&h|f&(l^h),n=y+o+a+Rw[u]+e[u],i=s+c,y=g,g=m,m=p,p=d+n>>>0,d=f,f=h,h=l,l=n+i>>>0;r.h0=r.h0+l|0,r.h1=r.h1+h|0,r.h2=r.h2+f|0,r.h3=r.h3+d|0,r.h4=r.h4+p|0,r.h5=r.h5+m|0,r.h6=r.h6+g|0,r.h7=r.h7+y|0,b-=64}}});var Cw=T((ste,Dw)=>{var vi=rt();Ft();var Df=null;vi.util.isNodejs&&!vi.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Df=Ns());var WN=Dw.exports=vi.prng=vi.prng||{};WN.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 h=e.plugin.cipher,f=e.plugin.increment,d=e.plugin.formatKey,p=e.plugin.formatSeed,m=vi.util.createBuffer();e.key=null,g();function g(y){if(y)return l(y);if(m.length()>=u)return l(null,m.getBytes(u));if(e.generated>1048575&&(e.key=null),e.key===null)return vi.util.nextTick(function(){s(g)});var b=h(e.key,e.seed);e.generated+=b.length,m.putBytes(b),e.key=d(h(e.key,f(e.seed))),e.seed=p(h(e.key,e.seed)),vi.util.setImmediate(g)}},e.generateSync=function(u){var l=e.plugin.cipher,h=e.plugin.increment,f=e.plugin.formatKey,d=e.plugin.formatSeed;e.key=null;for(var p=vi.util.createBuffer();p.length()<u;){e.generated>1048575&&(e.key=null),e.key===null&&o();var m=l(e.key,e.seed);e.generated+=m.length,p.putBytes(m),e.key=f(l(e.key,h(e.seed))),e.seed=d(l(e.key,e.seed))}return p.getBytes(u)};function s(u){if(e.pools[0].messageLength>=32)return a(),u();var l=32-e.pools[0].messageLength<<5;e.seedFile(l,function(h,f){if(h)return u(h);e.collect(f),a(),u()})}function o(){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,h=0;h<32;++h)e.reseeds%l===0&&(u.update(e.pools[h].digest().getBytes()),e.pools[h].start()),l=l<<1;e.keyBytes=u.digest().getBytes(),u.start(),u.update(e.keyBytes);var f=u.digest().getBytes();e.key=e.plugin.formatKey(e.keyBytes),e.seed=e.plugin.formatSeed(f),e.generated=0}function c(u){var l=null,h=vi.util.globalScope,f=h.crypto||h.msCrypto;f&&f.getRandomValues&&(l=function(v){return f.getRandomValues(v)});var d=vi.util.createBuffer();if(l)for(;d.length()<u;){var p=Math.max(1,Math.min(u-d.length(),65536)/4),m=new Uint32Array(Math.floor(p));try{l(m);for(var g=0;g<m.length;++g)d.putInt32(m[g])}catch(v){if(!(typeof QuotaExceededError<"u"&&v instanceof QuotaExceededError))throw v}}if(d.length()<u)for(var y,b,E,R=Math.floor(Math.random()*65536);d.length()<u;){b=16807*(R&65535),y=16807*(R>>16),b+=(y&32767)<<16,b+=y>>15,b=(b&2147483647)+(b>>31),R=b&4294967295;for(var g=0;g<3;++g)E=R>>>(g<<3),E^=Math.floor(Math.random()*256),d.putByte(E&255)}return d.getBytes(u)}return Df?(e.seedFile=function(u,l){Df.randomBytes(u,function(h,f){if(h)return l(h);l(null,f.toString())})},e.seedFileSync=function(u){return Df.randomBytes(u).toString()}):(e.seedFile=function(u,l){try{l(null,c(u))}catch(h){l(h)}},e.seedFileSync=c),e.collect=function(u){for(var l=u.length,h=0;h<l;++h)e.pools[e.pool].update(u.substr(h,1)),e.pool=e.pool===31?0:e.pool+1},e.collectInt=function(u,l){for(var h="",f=0;f<l;f+=8)h+=String.fromCharCode(u>>f&255);e.collect(h)},e.registerWorker=function(u){if(u===self)e.seedFile=function(h,f){function d(p){var m=p.data;m.forge&&m.forge.prng&&(self.removeEventListener("message",d),f(m.forge.prng.err,m.forge.prng.bytes))}self.addEventListener("message",d),self.postMessage({forge:{prng:{needed:h}}})};else{var l=function(h){var f=h.data;f.forge&&f.forge.prng&&e.seedFile(f.forge.prng.needed,function(d,p){u.postMessage({forge:{prng:{err:d,bytes:p}}})})};u.addEventListener("message",l)}},e}});var Vu=T((ote,g3)=>{var ir=rt();Sf();Tw();Cw();Ft();(function(){if(ir.random&&ir.random.getBytes){g3.exports=ir.random;return}(function(r){var e={},t=new Array(4),n=ir.util.createBuffer();e.formatKey=function(h){var f=ir.util.createBuffer(h);return h=new Array(4),h[0]=f.getInt32(),h[1]=f.getInt32(),h[2]=f.getInt32(),h[3]=f.getInt32(),ir.aes._expandKey(h,!1)},e.formatSeed=function(h){var f=ir.util.createBuffer(h);return h=new Array(4),h[0]=f.getInt32(),h[1]=f.getInt32(),h[2]=f.getInt32(),h[3]=f.getInt32(),h},e.cipher=function(h,f){return ir.aes._updateBlock(h,f,t,!1),n.putInt32(t[0]),n.putInt32(t[1]),n.putInt32(t[2]),n.putInt32(t[3]),n.getBytes()},e.increment=function(h){return++h[3],h},e.md=ir.md.sha256;function i(){var h=ir.prng.create(e);return h.getBytes=function(f,d){return h.generate(f,d)},h.getBytesSync=function(f){return h.generate(f)},h}var s=i(),o=null,a=ir.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(o=function(h){return c.getRandomValues(h)}),ir.options.usePureJavaScript||!ir.util.isNodejs&&!o){if(typeof window>"u"||window.document,s.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}s.collect(u),u=null}r&&(r().mousemove(function(h){s.collectInt(h.clientX,16),s.collectInt(h.clientY,16)}),r().keypress(function(h){s.collectInt(h.charCode,8)}))}if(!ir.random)ir.random=s;else for(var l in s)ir.random[l]=s[l];ir.random.createInstance=i,g3.exports=ir.random})(typeof jQuery<"u"?jQuery:null)})()});var Lw=T((ate,Nw)=>{var Vr=rt();Ft();var y3=[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],Pw=[1,2,3,5],YN=function(r,e){return r<<e&65535|(r&65535)>>16-e},QN=function(r,e){return(r&65535)>>e|r<<16-e&65535};Nw.exports=Vr.rc2=Vr.rc2||{};Vr.rc2.expandKey=function(r,e){typeof r=="string"&&(r=Vr.util.createBuffer(r)),e=e||128;var t=r,n=r.length(),i=e,s=Math.ceil(i/8),o=255>>(i&7),a;for(a=n;a<128;a++)t.putByte(y3[t.at(a-1)+t.at(a-n)&255]);for(t.setAt(128-s,y3[t.at(128-s)&o]),a=127-s;a>=0;a--)t.setAt(a,y3[t.at(a+1)^t.at(a+s)]);return t};var kw=function(r,e,t){var n=!1,i=null,s=null,o=null,a,c,u,l,h=[];for(r=Vr.rc2.expandKey(r,e),u=0;u<64;u++)h.push(r.getInt16Le());t?(a=function(p){for(u=0;u<4;u++)p[u]+=h[l]+(p[(u+3)%4]&p[(u+2)%4])+(~p[(u+3)%4]&p[(u+1)%4]),p[u]=YN(p[u],Pw[u]),l++},c=function(p){for(u=0;u<4;u++)p[u]+=h[p[(u+3)%4]&63]}):(a=function(p){for(u=3;u>=0;u--)p[u]=QN(p[u],Pw[u]),p[u]-=h[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]-=h[p[(u+3)%4]&63]});var f=function(p){var m=[];for(u=0;u<4;u++){var g=i.getInt16Le();o!==null&&(t?g^=o.getInt16Le():o.putInt16Le(g)),m.push(g&65535)}l=t?0:63;for(var y=0;y<p.length;y++)for(var b=0;b<p[y][0];b++)p[y][1](m);for(u=0;u<4;u++)o!==null&&(t?o.putInt16Le(m[u]):m[u]^=o.getInt16Le()),s.putInt16Le(m[u])},d=null;return d={start:function(p,m){p&&typeof p=="string"&&(p=Vr.util.createBuffer(p)),n=!1,i=Vr.util.createBuffer(),s=m||new Vr.util.createBuffer,o=p,d.output=s},update:function(p){for(n||i.putBuffer(p);i.length()>=8;)f([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(p){var m=!0;if(t)if(p)m=p(8,i,!t);else{var g=i.length()===8?8:8-i.length();i.fillWithByte(g,g)}if(m&&(n=!0,d.update()),!t&&(m=i.length()===0,m))if(p)m=p(8,s,!t);else{var y=s.length(),b=s.at(y-1);b>y?m=!1:s.truncate(b)}return m}},d};Vr.rc2.startEncrypting=function(r,e,t){var n=Vr.rc2.createEncryptionCipher(r,128);return n.start(e,t),n};Vr.rc2.createEncryptionCipher=function(r,e){return kw(r,e,!0)};Vr.rc2.startDecrypting=function(r,e,t){var n=Vr.rc2.createDecryptionCipher(r,128);return n.start(e,t),n};Vr.rc2.createDecryptionCipher=function(r,e){return kw(r,e,!1)}});var kf=T((cte,Vw)=>{var w3=rt();Vw.exports=w3.jsbn=w3.jsbn||{};var ji,XN=0xdeadbeefcafe,Ow=(XN&16777215)==15715070;function N(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))}w3.jsbn.BigInteger=N;function Ke(){return new N(null)}function jN(r,e,t,n,i,s){for(;--s>=0;){var o=e*this.data[r++]+t.data[n]+i;i=Math.floor(o/67108864),t.data[n++]=o&67108863}return i}function ZN(r,e,t,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this.data[r]&32767,u=this.data[r++]>>15,l=a*c+u*o;c=o*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 Bw(r,e,t,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this.data[r]&16383,u=this.data[r++]>>14,l=a*c+u*o;c=o*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"?(N.prototype.am=Bw,ji=28):Ow&&navigator.appName=="Microsoft Internet Explorer"?(N.prototype.am=ZN,ji=30):Ow&&navigator.appName!="Netscape"?(N.prototype.am=jN,ji=26):(N.prototype.am=Bw,ji=28);N.prototype.DB=ji;N.prototype.DM=(1<<ji)-1;N.prototype.DV=1<<ji;var b3=52;N.prototype.FV=Math.pow(2,b3);N.prototype.F1=b3-ji;N.prototype.F2=2*ji-b3;var JN="0123456789abcdefghijklmnopqrstuvwxyz",Cf=new Array,Ba,In;Ba="0".charCodeAt(0);for(In=0;In<=9;++In)Cf[Ba++]=In;Ba="a".charCodeAt(0);for(In=10;In<36;++In)Cf[Ba++]=In;Ba="A".charCodeAt(0);for(In=10;In<36;++In)Cf[Ba++]=In;function Mw(r){return JN.charAt(r)}function Uw(r,e){var t=Cf[r.charCodeAt(e)];return t??-1}function eL(r){for(var e=this.t-1;e>=0;--e)r.data[e]=this.data[e];r.t=this.t,r.s=this.s}function tL(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 Ls(r){var e=Ke();return e.fromInt(r),e}function rL(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,s=0;--n>=0;){var o=t==8?r[n]&255:Uw(r,n);if(o<0){r.charAt(n)=="-"&&(i=!0);continue}i=!1,s==0?this.data[this.t++]=o:s+t>this.DB?(this.data[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this.data[this.t++]=o>>this.DB-s):this.data[this.t-1]|=o<<s,s+=t,s>=this.DB&&(s-=this.DB)}t==8&&r[0]&128&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&N.ZERO.subTo(this,this)}function nL(){for(var r=this.s&this.DM;this.t>0&&this.data[this.t-1]==r;)--this.t}function iL(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<<e)-1,n,i=!1,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this.data[o]>>a)>0&&(i=!0,s=Mw(n));o>=0;)a<e?(n=(this.data[o]&(1<<a)-1)<<e-a,n|=this.data[--o]>>(a+=this.DB-e)):(n=this.data[o]>>(a-=e)&t,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=Mw(n));return i?s:"0"}function sL(){var r=Ke();return N.ZERO.subTo(this,r),r}function oL(){return this.s<0?this.negate():this}function aL(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 Pf(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 cL(){return this.t<=0?0:this.DB*(this.t-1)+Pf(this.data[this.t-1]^this.s&this.DM)}function uL(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 lL(r,e){for(var t=r;t<this.t;++t)e.data[t-r]=this.data[t];e.t=Math.max(this.t-r,0),e.s=this.s}function hL(r,e){var t=r%this.DB,n=this.DB-t,i=(1<<n)-1,s=Math.floor(r/this.DB),o=this.s<<t&this.DM,a;for(a=this.t-1;a>=0;--a)e.data[a+s+1]=this.data[a]>>n|o,o=(this.data[a]&i)<<t;for(a=s-1;a>=0;--a)e.data[a]=0;e.data[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp()}function fL(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,s=(1<<n)-1;e.data[0]=this.data[t]>>n;for(var o=t+1;o<this.t;++o)e.data[o-t-1]|=(this.data[o]&s)<<i,e.data[o-t]=this.data[o]>>n;n>0&&(e.data[this.t-t-1]|=(this.s&s)<<i),e.t=this.t-t,e.clamp()}function dL(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this.data[t]-r.data[t],e.data[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n-=r.s;t<this.t;)n+=this.data[t],e.data[t++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;t<r.t;)n-=r.data[t],e.data[t++]=n&this.DM,n>>=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 pL(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<n.t;++i)e.data[i+t.t]=t.am(0,n.data[i],e,i,0,t.t);e.s=0,e.clamp(),this.s!=r.s&&N.ZERO.subTo(e,e)}function mL(r){for(var e=this.abs(),t=r.t=2*e.t;--t>=0;)r.data[t]=0;for(t=0;t<e.t-1;++t){var n=e.am(t,e.data[t],r,2*t,0,1);(r.data[t+e.t]+=e.am(t+1,2*e.data[t],r,2*t+1,n,e.t-t-1))>=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 gL(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),t!=null&&this.copyTo(t);return}t==null&&(t=Ke());var s=Ke(),o=this.s,a=r.s,c=this.DB-Pf(n.data[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,t)):(n.copyTo(s),i.copyTo(t));var u=s.t,l=s.data[u-1];if(l!=0){var h=l*(1<<this.F1)+(u>1?s.data[u-2]>>this.F2:0),f=this.FV/h,d=(1<<this.F1)/h,p=1<<this.F2,m=t.t,g=m-u,y=e??Ke();for(s.dlShiftTo(g,y),t.compareTo(y)>=0&&(t.data[t.t++]=1,t.subTo(y,t)),N.ONE.dlShiftTo(u,y),y.subTo(s,s);s.t<u;)s.data[s.t++]=0;for(;--g>=0;){var b=t.data[--m]==l?this.DM:Math.floor(t.data[m]*f+(t.data[m-1]+p)*d);if((t.data[m]+=s.am(0,b,t,g,0,u))<b)for(s.dlShiftTo(g,y),t.subTo(y,t);t.data[m]<--b;)t.subTo(y,t)}e!=null&&(t.drShiftTo(u,e),o!=a&&N.ZERO.subTo(e,e)),t.t=u,t.clamp(),c>0&&t.rShiftTo(c,t),o<0&&N.ZERO.subTo(t,t)}}}function yL(r){var e=Ke();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(N.ZERO)>0&&r.subTo(e,e),e}function Po(r){this.m=r}function wL(r){return r.s<0||r.compareTo(this.m)>=0?r.mod(this.m):r}function bL(r){return r}function EL(r){r.divRemTo(this.m,null,r)}function vL(r,e,t){r.multiplyTo(e,t),this.reduce(t)}function xL(r,e){r.squareTo(e),this.reduce(e)}Po.prototype.convert=wL;Po.prototype.revert=bL;Po.prototype.reduce=EL;Po.prototype.mulTo=vL;Po.prototype.sqrTo=xL;function _L(){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 ko(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<r.DB-15)-1,this.mt2=2*r.t}function SL(r){var e=Ke();return r.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),r.s<0&&e.compareTo(N.ZERO)>0&&this.m.subTo(e,e),e}function AL(r){var e=Ke();return r.copyTo(e),this.reduce(e),e}function RL(r){for(;r.t<=this.mt2;)r.data[r.t++]=0;for(var e=0;e<this.m.t;++e){var t=r.data[e]&32767,n=t*this.mpl+((t*this.mph+(r.data[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 IL(r,e){r.squareTo(e),this.reduce(e)}function TL(r,e,t){r.multiplyTo(e,t),this.reduce(t)}ko.prototype.convert=SL;ko.prototype.revert=AL;ko.prototype.reduce=RL;ko.prototype.mulTo=TL;ko.prototype.sqrTo=IL;function DL(){return(this.t>0?this.data[0]&1:this.s)==0}function CL(r,e){if(r>4294967295||r<1)return N.ONE;var t=Ke(),n=Ke(),i=e.convert(this),s=Pf(r)-1;for(i.copyTo(t);--s>=0;)if(e.sqrTo(t,n),(r&1<<s)>0)e.mulTo(n,i,t);else{var o=t;t=n,n=o}return e.revert(t)}function PL(r,e){var t;return r<256||e.isEven()?t=new Po(e):t=new ko(e),this.exp(r,t)}N.prototype.copyTo=eL;N.prototype.fromInt=tL;N.prototype.fromString=rL;N.prototype.clamp=nL;N.prototype.dlShiftTo=uL;N.prototype.drShiftTo=lL;N.prototype.lShiftTo=hL;N.prototype.rShiftTo=fL;N.prototype.subTo=dL;N.prototype.multiplyTo=pL;N.prototype.squareTo=mL;N.prototype.divRemTo=gL;N.prototype.invDigit=_L;N.prototype.isEven=DL;N.prototype.exp=CL;N.prototype.toString=iL;N.prototype.negate=sL;N.prototype.abs=oL;N.prototype.compareTo=aL;N.prototype.bitLength=cL;N.prototype.mod=yL;N.prototype.modPowInt=PL;N.ZERO=Ls(0);N.ONE=Ls(1);function kL(){var r=Ke();return this.copyTo(r),r}function NL(){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)<<this.DB|this.data[0]}function LL(){return this.t==0?this.s:this.data[0]<<24>>24}function OL(){return this.t==0?this.s:this.data[0]<<16>>16}function BL(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function ML(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function UL(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=Ls(t),i=Ke(),s=Ke(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(t+s.intValue()).toString(r).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(r)+o}function FL(r,e){this.fromInt(0),e==null&&(e=10);for(var t=this.chunkSize(e),n=Math.pow(e,t),i=!1,s=0,o=0,a=0;a<r.length;++a){var c=Uw(r,a);if(c<0){r.charAt(a)=="-"&&this.signum()==0&&(i=!0);continue}o=e*o+c,++s>=t&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),i&&N.ZERO.subTo(this,this)}function KL(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(N.ONE.shiftLeft(r-1),E3,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>r&&this.subTo(N.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<<i)-1:n[0]=0,this.fromString(n,256)}}function qL(){var r=this.t,e=new Array;e[0]=this.s;var t=this.DB-r*this.DB%8,n,i=0;if(r-- >0)for(t<this.DB&&(n=this.data[r]>>t)!=(this.s&this.DM)>>t&&(e[i++]=n|this.s<<this.DB-t);r>=0;)t<8?(n=(this.data[r]&(1<<t)-1)<<8-t,n|=this.data[--r]>>(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 VL(r){return this.compareTo(r)==0}function zL(r){return this.compareTo(r)<0?this:r}function HL(r){return this.compareTo(r)>0?this:r}function $L(r,e,t){var n,i,s=Math.min(r.t,this.t);for(n=0;n<s;++n)t.data[n]=e(this.data[n],r.data[n]);if(r.t<this.t){for(i=r.s&this.DM,n=s;n<this.t;++n)t.data[n]=e(this.data[n],i);t.t=this.t}else{for(i=this.s&this.DM,n=s;n<r.t;++n)t.data[n]=e(i,r.data[n]);t.t=r.t}t.s=e(this.s,r.s),t.clamp()}function GL(r,e){return r&e}function WL(r){var e=Ke();return this.bitwiseTo(r,GL,e),e}function E3(r,e){return r|e}function YL(r){var e=Ke();return this.bitwiseTo(r,E3,e),e}function Fw(r,e){return r^e}function QL(r){var e=Ke();return this.bitwiseTo(r,Fw,e),e}function Kw(r,e){return r&~e}function XL(r){var e=Ke();return this.bitwiseTo(r,Kw,e),e}function jL(){for(var r=Ke(),e=0;e<this.t;++e)r.data[e]=this.DM&~this.data[e];return r.t=this.t,r.s=~this.s,r}function ZL(r){var e=Ke();return r<0?this.rShiftTo(-r,e):this.lShiftTo(r,e),e}function JL(r){var e=Ke();return r<0?this.lShiftTo(-r,e):this.rShiftTo(r,e),e}function eO(r){if(r==0)return-1;var e=0;return r&65535||(r>>=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 tO(){for(var r=0;r<this.t;++r)if(this.data[r]!=0)return r*this.DB+eO(this.data[r]);return this.s<0?this.t*this.DB:-1}function rO(r){for(var e=0;r!=0;)r&=r-1,++e;return e}function nO(){for(var r=0,e=this.s&this.DM,t=0;t<this.t;++t)r+=rO(this.data[t]^e);return r}function iO(r){var e=Math.floor(r/this.DB);return e>=this.t?this.s!=0:(this.data[e]&1<<r%this.DB)!=0}function sO(r,e){var t=N.ONE.shiftLeft(r);return this.bitwiseTo(t,e,t),t}function oO(r){return this.changeBit(r,E3)}function aO(r){return this.changeBit(r,Kw)}function cO(r){return this.changeBit(r,Fw)}function uO(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this.data[t]+r.data[t],e.data[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n+=r.s;t<this.t;)n+=this.data[t],e.data[t++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;t<r.t;)n+=r.data[t],e.data[t++]=n&this.DM,n>>=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 lO(r){var e=Ke();return this.addTo(r,e),e}function hO(r){var e=Ke();return this.subTo(r,e),e}function fO(r){var e=Ke();return this.multiplyTo(r,e),e}function dO(r){var e=Ke();return this.divRemTo(r,e,null),e}function pO(r){var e=Ke();return this.divRemTo(r,null,e),e}function mO(r){var e=Ke(),t=Ke();return this.divRemTo(r,e,t),new Array(e,t)}function gO(r){this.data[this.t]=this.am(0,r-1,this,0,0,this.t),++this.t,this.clamp()}function yO(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 zu(){}function qw(r){return r}function wO(r,e,t){r.multiplyTo(e,t)}function bO(r,e){r.squareTo(e)}zu.prototype.convert=qw;zu.prototype.revert=qw;zu.prototype.mulTo=wO;zu.prototype.sqrTo=bO;function EO(r){return this.exp(r,new zu)}function vO(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<i;++n)t.data[n+this.t]=this.am(0,r.data[n],t,n,0,this.t);for(i=Math.min(r.t,e);n<i;++n)this.am(0,r.data[n],t,n,0,e-n);t.clamp()}function xO(r,e,t){--e;var n=t.t=this.t+r.t-e;for(t.s=0;--n>=0;)t.data[n]=0;for(n=Math.max(e-this.t,0);n<r.t;++n)t.data[this.t+n-e]=this.am(e-n,r.data[n],t,0,0,this.t+n-e);t.clamp(),t.drShiftTo(1,t)}function Ma(r){this.r2=Ke(),this.q3=Ke(),N.ONE.dlShiftTo(2*r.t,this.r2),this.mu=this.r2.divide(r),this.m=r}function _O(r){if(r.s<0||r.t>2*this.m.t)return r.mod(this.m);if(r.compareTo(this.m)<0)return r;var e=Ke();return r.copyTo(e),this.reduce(e),e}function SO(r){return r}function AO(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 RO(r,e){r.squareTo(e),this.reduce(e)}function IO(r,e,t){r.multiplyTo(e,t),this.reduce(t)}Ma.prototype.convert=_O;Ma.prototype.revert=SO;Ma.prototype.reduce=AO;Ma.prototype.mulTo=IO;Ma.prototype.sqrTo=RO;function TO(r,e){var t=r.bitLength(),n,i=Ls(1),s;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?s=new Po(e):e.isEven()?s=new Ma(e):s=new ko(e);var o=new Array,a=3,c=n-1,u=(1<<n)-1;if(o[1]=s.convert(this),n>1){var l=Ke();for(s.sqrTo(o[1],l);a<=u;)o[a]=Ke(),s.mulTo(l,o[a-2],o[a]),a+=2}var h=r.t-1,f,d=!0,p=Ke(),m;for(t=Pf(r.data[h])-1;h>=0;){for(t>=c?f=r.data[h]>>t-c&u:(f=(r.data[h]&(1<<t+1)-1)<<c-t,h>0&&(f|=r.data[h-1]>>this.DB+t-c)),a=n;!(f&1);)f>>=1,--a;if((t-=a)<0&&(t+=this.DB,--h),d)o[f].copyTo(i),d=!1;else{for(;a>1;)s.sqrTo(i,p),s.sqrTo(p,i),a-=2;a>0?s.sqrTo(i,p):(m=i,i=p,p=m),s.mulTo(p,o[f],i)}for(;h>=0&&!(r.data[h]&1<<t);)s.sqrTo(i,p),m=i,i=p,p=m,--t<0&&(t=this.DB-1,--h)}return s.revert(i)}function DO(r){var e=this.s<0?this.negate():this.clone(),t=r.s<0?r.negate():r.clone();if(e.compareTo(t)<0){var n=e;e=t,t=n}var i=e.getLowestSetBit(),s=t.getLowestSetBit();if(s<0)return e;for(i<s&&(s=i),s>0&&(e.rShiftTo(s,e),t.rShiftTo(s,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 s>0&&t.lShiftTo(s,t),t}function CO(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 PO(r){var e=r.isEven();if(this.isEven()&&e||r.signum()==0)return N.ZERO;for(var t=r.clone(),n=this.clone(),i=Ls(1),s=Ls(0),o=Ls(0),a=Ls(1);t.signum()!=0;){for(;t.isEven();)t.rShiftTo(1,t),e?((!i.isEven()||!s.isEven())&&(i.addTo(this,i),s.subTo(r,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(r,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!a.isEven())&&(o.addTo(this,o),a.subTo(r,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(r,a),a.rShiftTo(1,a);t.compareTo(n)>=0?(t.subTo(n,t),e&&i.subTo(o,i),s.subTo(a,s)):(n.subTo(t,n),e&&o.subTo(i,o),a.subTo(s,a))}if(n.compareTo(N.ONE)!=0)return N.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 Yn=[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],kO=(1<<26)/Yn[Yn.length-1];function NO(r){var e,t=this.abs();if(t.t==1&&t.data[0]<=Yn[Yn.length-1]){for(e=0;e<Yn.length;++e)if(t.data[0]==Yn[e])return!0;return!1}if(t.isEven())return!1;for(e=1;e<Yn.length;){for(var n=Yn[e],i=e+1;i<Yn.length&&n<kO;)n*=Yn[i++];for(n=t.modInt(n);e<i;)if(n%Yn[e++]==0)return!1}return t.millerRabin(r)}function LO(r){var e=this.subtract(N.ONE),t=e.getLowestSetBit();if(t<=0)return!1;for(var n=e.shiftRight(t),i=OO(),s,o=0;o<r;++o){do s=new N(this.bitLength(),i);while(s.compareTo(N.ONE)<=0||s.compareTo(e)>=0);var a=s.modPow(n,this);if(a.compareTo(N.ONE)!=0&&a.compareTo(e)!=0){for(var c=1;c++<t&&a.compareTo(e)!=0;)if(a=a.modPowInt(2,this),a.compareTo(N.ONE)==0)return!1;if(a.compareTo(e)!=0)return!1}}return!0}function OO(){return{nextBytes:function(r){for(var e=0;e<r.length;++e)r[e]=Math.floor(Math.random()*256)}}}N.prototype.chunkSize=BL;N.prototype.toRadix=UL;N.prototype.fromRadix=FL;N.prototype.fromNumber=KL;N.prototype.bitwiseTo=$L;N.prototype.changeBit=sO;N.prototype.addTo=uO;N.prototype.dMultiply=gO;N.prototype.dAddOffset=yO;N.prototype.multiplyLowerTo=vO;N.prototype.multiplyUpperTo=xO;N.prototype.modInt=CO;N.prototype.millerRabin=LO;N.prototype.clone=kL;N.prototype.intValue=NL;N.prototype.byteValue=LL;N.prototype.shortValue=OL;N.prototype.signum=ML;N.prototype.toByteArray=qL;N.prototype.equals=VL;N.prototype.min=zL;N.prototype.max=HL;N.prototype.and=WL;N.prototype.or=YL;N.prototype.xor=QL;N.prototype.andNot=XL;N.prototype.not=jL;N.prototype.shiftLeft=ZL;N.prototype.shiftRight=JL;N.prototype.getLowestSetBit=tO;N.prototype.bitCount=nO;N.prototype.testBit=iO;N.prototype.setBit=oO;N.prototype.clearBit=aO;N.prototype.flipBit=cO;N.prototype.add=lO;N.prototype.subtract=hO;N.prototype.multiply=fO;N.prototype.divide=dO;N.prototype.remainder=pO;N.prototype.divideAndRemainder=mO;N.prototype.modPow=TO;N.prototype.modInverse=PO;N.prototype.pow=EO;N.prototype.gcd=DO;N.prototype.isProbablePrime=NO});var Ww=T((ute,Gw)=>{var xi=rt();Co();Ft();var Hw=Gw.exports=xi.sha1=xi.sha1||{};xi.md.sha1=xi.md.algorithms.sha1=Hw;Hw.create=function(){$w||BO();var r=null,e=xi.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,s=0;s<i;++s)n.fullMessageLength.push(0);return e=xi.util.createBuffer(),r={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},n},n.start(),n.update=function(i,s){s==="utf8"&&(i=xi.util.encodeUtf8(i));var o=i.length;n.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=o[1],o[1]=o[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return e.putBytes(i),zw(r,t,e),(e.read>2048||e.length()===0)&&e.compact(),n},n.digest=function(){var i=xi.util.createBuffer();i.putBytes(e.bytes());var s=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,o=s&n.blockLength-1;i.putBytes(v3.substr(0,n.blockLength-o));for(var a,c,u=n.fullMessageLength[0]*8,l=0;l<n.fullMessageLength.length-1;++l)a=n.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var h={h0:r.h0,h1:r.h1,h2:r.h2,h3:r.h3,h4:r.h4};zw(h,t,i);var f=xi.util.createBuffer();return f.putInt32(h.h0),f.putInt32(h.h1),f.putInt32(h.h2),f.putInt32(h.h3),f.putInt32(h.h4),f},n};var v3=null,$w=!1;function BO(){v3=String.fromCharCode(128),v3+=xi.util.fillString(String.fromCharCode(0),64),$w=!0}function zw(r,e,t){for(var n,i,s,o,a,c,u,l,h=t.length();h>=64;){for(i=r.h0,s=r.h1,o=r.h2,a=r.h3,c=r.h4,l=0;l<16;++l)n=t.getInt32(),e[l]=n,u=a^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=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^s&(o^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=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=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=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=s^o^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=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=s&o|a&(s^o),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=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=s^o^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;r.h0=r.h0+i|0,r.h1=r.h1+s|0,r.h2=r.h2+o|0,r.h3=r.h3+a|0,r.h4=r.h4+c|0,h-=64}}});var Xw=T((lte,Qw)=>{var _i=rt();Ft();Vu();Ww();var Yw=Qw.exports=_i.pkcs1=_i.pkcs1||{};Yw.encode_rsa_oaep=function(r,e,t){var n,i,s,o;typeof t=="string"?(n=t,i=arguments[3]||void 0,s=arguments[4]||void 0):t&&(n=t.label||void 0,i=t.seed||void 0,s=t.md||void 0,t.mgf1&&t.mgf1.md&&(o=t.mgf1.md)),s?s.start():s=_i.md.sha1.create(),o||(o=s);var a=Math.ceil(r.n.bitLength()/8),c=a-2*s.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=""),s.update(n,"raw");for(var l=s.digest(),h="",f=c-e.length,d=0;d<f;d++)h+="\0";var p=l.getBytes()+h+""+e;if(!i)i=_i.random.getBytes(s.digestLength);else if(i.length!==s.digestLength){var u=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=s.digestLength,u}var m=Nf(i,a-s.digestLength-1,o),g=_i.util.xorBytes(p,m,p.length),y=Nf(g,s.digestLength,o),b=_i.util.xorBytes(i,y,i.length);return"\0"+b+g};Yw.decode_rsa_oaep=function(r,e,t){var n,i,s;typeof t=="string"?(n=t,i=arguments[3]||void 0):t&&(n=t.label||void 0,i=t.md||void 0,t.mgf1&&t.mgf1.md&&(s=t.mgf1.md));var o=Math.ceil(r.n.bitLength()/8);if(e.length!==o){var g=new Error("RSAES-OAEP encoded message length is invalid.");throw g.length=e.length,g.expectedLength=o,g}if(i===void 0?i=_i.md.sha1.create():i.start(),s||(s=i),o<2*i.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");n||(n=""),i.update(n,"raw");for(var a=i.digest().getBytes(),c=e.charAt(0),u=e.substring(1,i.digestLength+1),l=e.substring(1+i.digestLength),h=Nf(l,i.digestLength,s),f=_i.util.xorBytes(u,h,u.length),d=Nf(f,o-i.digestLength-1,s),p=_i.util.xorBytes(l,d,l.length),m=p.substring(0,i.digestLength),g=c!=="\0",y=0;y<i.digestLength;++y)g|=a.charAt(y)!==m.charAt(y);for(var b=1,E=i.digestLength,R=i.digestLength;R<p.length;R++){var v=p.charCodeAt(R),_=v&1^1,I=b?65534:0;g|=v&I,b=b&_,E+=b}if(g||p.charCodeAt(E)!==1)throw new Error("Invalid RSAES-OAEP padding.");return p.substring(E+1)};function Nf(r,e,t){t||(t=_i.md.sha1.create());for(var n="",i=Math.ceil(e/t.digestLength),s=0;s<i;++s){var o=String.fromCharCode(s>>24&255,s>>16&255,s>>8&255,s&255);t.start(),t.update(r+o),n+=t.digest().getBytes()}return n.substring(0,e)}});var jw=T((hte,x3)=>{var Os=rt();Ft();kf();Vu();(function(){if(Os.prime){x3.exports=Os.prime;return}var r=x3.exports=Os.prime=Os.prime||{},e=Os.jsbn.BigInteger,t=[6,4,2,4,2,4,6,2],n=new e(null);n.fromInt(30);var i=function(h,f){return h|f};r.generateProbablePrime=function(h,f,d){typeof f=="function"&&(d=f,f={}),f=f||{};var p=f.algorithm||"PRIMEINC";typeof p=="string"&&(p={name:p}),p.options=p.options||{};var m=f.prng||Os.random,g={nextBytes:function(y){for(var b=m.getBytesSync(y.length),E=0;E<y.length;++E)y[E]=b.charCodeAt(E)}};if(p.name==="PRIMEINC")return s(h,g,p.options,d);throw new Error("Invalid prime generation algorithm: "+p.name)};function s(h,f,d,p){return"workers"in d?c(h,f,d,p):o(h,f,d,p)}function o(h,f,d,p){var m=u(h,f),g=0,y=l(m.bitLength());"millerRabinTests"in d&&(y=d.millerRabinTests);var b=10;"maxBlockTime"in d&&(b=d.maxBlockTime),a(m,h,f,g,y,b,p)}function a(h,f,d,p,m,g,y){var b=+new Date;do{if(h.bitLength()>f&&(h=u(f,d)),h.isProbablePrime(m))return y(null,h);h.dAddOffset(t[p++%8],0)}while(g<0||+new Date-b<g);Os.util.setImmediate(function(){a(h,f,d,p,m,g,y)})}function c(h,f,d,p){if(typeof Worker>"u")return o(h,f,d,p);var m=u(h,f),g=d.workers,y=d.workLoad||100,b=y*30/8,E=d.workerScript||"forge/prime.worker.js";if(g===-1)return Os.util.estimateCores(function(v,_){v&&(_=2),g=_-1,R()});R();function R(){g=Math.max(1,g);for(var v=[],_=0;_<g;++_)v[_]=new Worker(E);for(var I=g,_=0;_<g;++_)v[_].addEventListener("message",M);var P=!1;function M(W){if(!P){--I;var ue=W.data;if(ue.found){for(var le=0;le<v.length;++le)v[le].terminate();return P=!0,p(null,new e(ue.prime,16))}m.bitLength()>h&&(m=u(h,f));var Ce=m.toString(16);W.target.postMessage({hex:Ce,workLoad:y}),m.dAddOffset(b,0)}}}}function u(h,f){var d=new e(h,f),p=h-1;return d.testBit(p)||d.bitwiseTo(e.ONE.shiftLeft(p),i,d),d.dAddOffset(31-d.mod(n).byteValue(),0),d}function l(h){return h<=100?27:h<=150?18:h<=200?15:h<=250?12:h<=300?9:h<=350?8:h<=400?7:h<=500?6:h<=600?5:h<=800?4:h<=1250?3:2}})()});var Of=T((fte,ib)=>{var te=rt();qu();kf();bf();Xw();jw();Vu();Ft();typeof ke>"u"&&(ke=te.jsbn.BigInteger);var ke,_3=te.util.isNodejs?Ns():null,A=te.asn1,Tn=te.util;te.pki=te.pki||{};ib.exports=te.pki.rsa=te.rsa=te.rsa||{};var ge=te.pki,MO=[6,4,2,4,2,4,6,2],UO={name:"PrivateKeyInfo",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:A.Class.UNIVERSAL,type:A.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},FO={name:"RSAPrivateKey",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},KO={name:"RSAPublicKey",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},qO=te.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:A.Class.UNIVERSAL,type:A.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},VO={name:"DigestInfo",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:A.Class.UNIVERSAL,type:A.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:A.Class.UNIVERSAL,type:A.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},zO=function(r){var e;if(r.algorithm in ge.oids)e=ge.oids[r.algorithm];else{var t=new Error("Unknown message digest algorithm.");throw t.algorithm=r.algorithm,t}var n=A.oidToDer(e).getBytes(),i=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[]),s=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[]);s.value.push(A.create(A.Class.UNIVERSAL,A.Type.OID,!1,n)),s.value.push(A.create(A.Class.UNIVERSAL,A.Type.NULL,!1,""));var o=A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,r.digest().getBytes());return i.value.push(s),i.value.push(o),A.toDer(i).getBytes()},rb=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(ke.ONE))),e.dQ||(e.dQ=e.d.mod(e.q.subtract(ke.ONE))),e.qInv||(e.qInv=e.q.modInverse(e.p));var n;do n=new ke(te.util.bytesToHex(te.random.getBytes(e.n.bitLength()/8)),16);while(n.compareTo(e.n)>=0||!n.gcd(e.n).equals(ke.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),s=r.mod(e.q).modPow(e.dQ,e.q);i.compareTo(s)<0;)i=i.add(e.p);var o=i.subtract(s).multiply(e.qInv).mod(e.p).multiply(e.q).add(s);return o=o.multiply(n.modInverse(e.n)).mod(e.n),o};ge.rsa.encrypt=function(r,e,t){var n=t,i,s=Math.ceil(e.n.bitLength()/8);t!==!1&&t!==!0?(n=t===2,i=nb(r,e,t)):(i=te.util.createBuffer(),i.putBytes(r));for(var o=new ke(i.toHex(),16),a=rb(o,e,n),c=a.toString(16),u=te.util.createBuffer(),l=s-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(te.util.hexToBytes(c)),u.getBytes()};ge.rsa.decrypt=function(r,e,t,n){var i=Math.ceil(e.n.bitLength()/8);if(r.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=r.length,s.expected=i,s}var o=new ke(te.util.createBuffer(r).toHex(),16);if(o.compareTo(e.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=rb(o,e,t),c=a.toString(16),u=te.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(te.util.hexToBytes(c)),n!==!1?Lf(u.getBytes(),e,t):u.getBytes()};ge.rsa.createKeyPairGenerationState=function(r,e,t){typeof r=="string"&&(r=parseInt(r,10)),r=r||2048,t=t||{};var n=t.prng||te.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},s=t.algorithm||"PRIMEINC",o;if(s==="PRIMEINC")o={algorithm:s,state:0,bits:r,rng:i,eInt:e||65537,e:new ke(null),p:null,q:null,qBits:r>>1,pBits:r-(r>>1),pqState:0,num:null,keys:null},o.e.fromInt(o.eInt);else throw new Error("Invalid key generation algorithm: "+s);return o};ge.rsa.stepKeyPairGenerationState=function(r,e){"algorithm"in r||(r.algorithm="PRIMEINC");var t=new ke(null);t.fromInt(30);for(var n=0,i=function(h,f){return h|f},s=+new Date,o,a=0;r.keys===null&&(e<=0||a<e);){if(r.state===0){var c=r.p===null?r.pBits:r.qBits,u=c-1;r.pqState===0?(r.num=new ke(c,r.rng),r.num.testBit(u)||r.num.bitwiseTo(ke.ONE.shiftLeft(u),i,r.num),r.num.dAddOffset(31-r.num.mod(t).byteValue(),0),n=0,++r.pqState):r.pqState===1?r.num.bitLength()>c?r.pqState=0:r.num.isProbablePrime($O(r.num.bitLength()))?++r.pqState:r.num.dAddOffset(MO[n++%8],0):r.pqState===2?r.pqState=r.num.subtract(ke.ONE).gcd(r.e).compareTo(ke.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(ke.ONE),r.q1=r.q.subtract(ke.ONE),r.phi=r.p1.multiply(r.q1),++r.state;else if(r.state===3)r.phi.gcd(r.e).compareTo(ke.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:ge.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:ge.rsa.setPublicKey(r.n,r.e)}}o=+new Date,a+=o-s,s=o}return r.keys!==null};ge.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),!te.options.usePureJavaScript&&!t.prng&&r>=256&&r<=16384&&(e===65537||e===3)){if(n){if(Zw("generateKeyPair"))return _3.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:ge.privateKeyFromPem(u),publicKey:ge.publicKeyFromPem(c)})});if(Jw("generateKey")&&Jw("exportKey"))return Tn.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:tb(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Tn.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=ge.privateKeyFromAsn1(A.fromDer(te.util.createBuffer(a)));n(null,{privateKey:c,publicKey:ge.setRsaPublicKey(c.n,c.e)})}});if(eb("generateKey")&&eb("exportKey")){var i=Tn.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:tb(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Tn.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var h=l.target.result,f=ge.privateKeyFromAsn1(A.fromDer(te.util.createBuffer(h)));n(null,{privateKey:f,publicKey:ge.setRsaPublicKey(f.n,f.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(Zw("generateKeyPairSync")){var s=_3.generateKeyPairSync("rsa",{modulusLength:r,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:ge.privateKeyFromPem(s.privateKey),publicKey:ge.publicKeyFromPem(s.publicKey)}}}var o=ge.rsa.createKeyPairGenerationState(r,e,t);if(!n)return ge.rsa.stepKeyPairGenerationState(o,0),o.keys;HO(o,t,n)};ge.setRsaPublicKey=ge.rsa.setPublicKey=function(r,e){var t={n:r,e};return t.encrypt=function(n,i,s){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 nb(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return te.pkcs1.encode_rsa_oaep(c,a,s)}};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 o=i.encode(n,t,!0);return ge.rsa.encrypt(o,t,!0)},t.verify=function(n,i,s,o){typeof s=="string"?s=s.toUpperCase():s===void 0&&(s="RSASSA-PKCS1-V1_5"),o===void 0&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),s==="RSASSA-PKCS1-V1_5"?s={verify:function(c,u){u=Lf(u,t,!0);var l=A.fromDer(u,{parseAllBytes:o._parseAllDigestBytes}),h={},f=[];if(!A.validate(l,VO,h,f)){var d=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw d.errors=f,d}var p=A.derToOid(h.algorithmIdentifier);if(!(p===te.oids.md2||p===te.oids.md5||p===te.oids.sha1||p===te.oids.sha224||p===te.oids.sha256||p===te.oids.sha384||p===te.oids.sha512||p===te.oids["sha512-224"]||p===te.oids["sha512-256"])){var d=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw d.oid=p,d}if((p===te.oids.md2||p===te.oids.md5)&&!("parameters"in h))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===h.digest}}:(s==="NONE"||s==="NULL"||s===null)&&(s={verify:function(c,u){return u=Lf(u,t,!0),c===u}});var a=ge.rsa.decrypt(i,t,!0,!1);return s.verify(n,a,t.n.bitLength())},t};ge.setRsaPrivateKey=ge.rsa.setPrivateKey=function(r,e,t,n,i,s,o,a){var c={n:r,e,d:t,p:n,q:i,dP:s,dQ:o,qInv:a};return c.decrypt=function(u,l,h){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var f=ge.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:Lf};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(d,p){return te.pkcs1.decode_rsa_oaep(p,d,h)}};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(f,c,!1)},c.sign=function(u,l){var h=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:zO},h=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},h=1);var f=l.encode(u,c.n.bitLength());return ge.rsa.encrypt(f,c,h)},c};ge.wrapRsaPrivateKey=function(r){return A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,A.integerToDer(0).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(ge.oids.rsaEncryption).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.NULL,!1,"")]),A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,A.toDer(r).getBytes())])};ge.privateKeyFromAsn1=function(r){var e={},t=[];if(A.validate(r,UO,e,t)&&(r=A.fromDer(te.util.createBuffer(e.privateKey))),e={},t=[],!A.validate(r,FO,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,s,o,a,c,u,l,h;return i=te.util.createBuffer(e.privateKeyModulus).toHex(),s=te.util.createBuffer(e.privateKeyPublicExponent).toHex(),o=te.util.createBuffer(e.privateKeyPrivateExponent).toHex(),a=te.util.createBuffer(e.privateKeyPrime1).toHex(),c=te.util.createBuffer(e.privateKeyPrime2).toHex(),u=te.util.createBuffer(e.privateKeyExponent1).toHex(),l=te.util.createBuffer(e.privateKeyExponent2).toHex(),h=te.util.createBuffer(e.privateKeyCoefficient).toHex(),ge.setRsaPrivateKey(new ke(i,16),new ke(s,16),new ke(o,16),new ke(a,16),new ke(c,16),new ke(u,16),new ke(l,16),new ke(h,16))};ge.privateKeyToAsn1=ge.privateKeyToRSAPrivateKey=function(r){return A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,A.integerToDer(0).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.n)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.e)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.d)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.p)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.q)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.dP)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.dQ)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.qInv))])};ge.publicKeyFromAsn1=function(r){var e={},t=[];if(A.validate(r,qO,e,t)){var n=A.derToOid(e.publicKeyOid);if(n!==ge.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}r=e.rsaPublicKey}if(t=[],!A.validate(r,KO,e,t)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=t,i}var s=te.util.createBuffer(e.publicKeyModulus).toHex(),o=te.util.createBuffer(e.publicKeyExponent).toHex();return ge.setRsaPublicKey(new ke(s,16),new ke(o,16))};ge.publicKeyToAsn1=ge.publicKeyToSubjectPublicKeyInfo=function(r){return A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(ge.oids.rsaEncryption).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.NULL,!1,"")]),A.create(A.Class.UNIVERSAL,A.Type.BITSTRING,!1,[ge.publicKeyToRSAPublicKey(r)])])};ge.publicKeyToRSAPublicKey=function(r){return A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.n)),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,Si(r.e))])};function nb(r,e,t){var n=te.util.createBuffer(),i=Math.ceil(e.n.bitLength()/8);if(r.length>i-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=r.length,s.max=i-11,s}n.putByte(0),n.putByte(t);var o=i-3-r.length,a;if(t===0||t===1){a=t===0?0:255;for(var c=0;c<o;++c)n.putByte(a)}else for(;o>0;){for(var u=0,l=te.random.getBytes(o),c=0;c<o;++c)a=l.charCodeAt(c),a===0?++u:n.putByte(a);o=u}return n.putByte(0),n.putBytes(r),n}function Lf(r,e,t,n){var i=Math.ceil(e.n.bitLength()/8),s=te.util.createBuffer(r),o=s.getByte(),a=s.getByte();if(o!==0||t&&a!==0&&a!==1||!t&&a!=2||t&&a===0&&typeof n>"u")throw new Error("Encryption block is invalid.");var c=0;if(a===0){c=i-3-n;for(var u=0;u<c;++u)if(s.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(a===1)for(c=0;s.length()>1;){if(s.getByte()!==255){--s.read;break}++c}else if(a===2)for(c=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++c}var l=s.getByte();if(l!==0||c!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function HO(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(){s(r.pBits,function(a,c){if(a)return t(a);if(r.p=c,r.q!==null)return o(a,r.q);s(r.qBits,o)})}function s(a,c){te.prime.generateProbablePrime(a,n,c)}function o(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(ke.ONE).gcd(r.e).compareTo(ke.ONE)!==0){r.p=null,i();return}if(r.q.subtract(ke.ONE).gcd(r.e).compareTo(ke.ONE)!==0){r.q=null,s(r.qBits,o);return}if(r.p1=r.p.subtract(ke.ONE),r.q1=r.q.subtract(ke.ONE),r.phi=r.p1.multiply(r.q1),r.phi.gcd(r.e).compareTo(ke.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,s(r.qBits,o);return}var l=r.e.modInverse(r.phi);r.keys={privateKey:ge.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:ge.rsa.setPublicKey(r.n,r.e)},t(null,r.keys)}}function Si(r){var e=r.toString(16);e[0]>="8"&&(e="00"+e);var t=te.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 $O(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 Zw(r){return te.util.isNodejs&&typeof _3[r]=="function"}function Jw(r){return typeof Tn.globalScope<"u"&&typeof Tn.globalScope.crypto=="object"&&typeof Tn.globalScope.crypto.subtle=="object"&&typeof Tn.globalScope.crypto.subtle[r]=="function"}function eb(r){return typeof Tn.globalScope<"u"&&typeof Tn.globalScope.msCrypto=="object"&&typeof Tn.globalScope.msCrypto.subtle=="object"&&typeof Tn.globalScope.msCrypto.subtle[r]=="function"}function tb(r){for(var e=te.util.hexToBytes(r.toString(16)),t=new Uint8Array(e.length),n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}});var lb=T((dte,ub)=>{var H=rt();Sf();qu();mw();Co();bf();p3();xw();Vu();Lw();Of();Ft();typeof sb>"u"&&(sb=H.jsbn.BigInteger);var sb,C=H.asn1,ye=H.pki=H.pki||{};ub.exports=ye.pbe=H.pbe=H.pbe||{};var No=ye.oids,GO={name:"EncryptedPrivateKeyInfo",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},WO={name:"PBES2Algorithms",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},YO={name:"pkcs-12PbeParams",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,capture:"iterations"}]};ye.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=H.random.getBytesSync(t.saltSize),i=t.count,s=C.integerToDer(i),o,a,c;if(t.algorithm.indexOf("aes")===0||t.algorithm==="des"){var u,l,h;switch(t.algorithm){case"aes128":o=16,u=16,l=No["aes128-CBC"],h=H.aes.createEncryptionCipher;break;case"aes192":o=24,u=16,l=No["aes192-CBC"],h=H.aes.createEncryptionCipher;break;case"aes256":o=32,u=16,l=No["aes256-CBC"],h=H.aes.createEncryptionCipher;break;case"des":o=8,u=8,l=No.desCBC,h=H.des.createEncryptionCipher;break;default:var f=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw f.algorithm=t.algorithm,f}var d="hmacWith"+t.prfAlgorithm.toUpperCase(),p=cb(d),m=H.pkcs5.pbkdf2(e,n,i,o,p),g=H.random.getBytesSync(u),y=h(m);y.start(g),y.update(C.toDer(r)),y.finish(),c=y.output.getBytes();var b=QO(n,s,o,d);a=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(No.pkcs5PBES2).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(No.pkcs5PBKDF2).getBytes()),b]),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(l).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,g)])])])}else if(t.algorithm==="3des"){o=24;var E=new H.util.ByteBuffer(n),m=ye.pbe.generatePkcs12Key(e,E,1,i,o),g=ye.pbe.generatePkcs12Key(e,E,2,i,o),y=H.des.createEncryptionCipher(m);y.start(g),y.update(C.toDer(r)),y.finish(),c=y.output.getBytes(),a=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(No["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,n),C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,s.getBytes())])])}else{var f=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw f.algorithm=t.algorithm,f}var R=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[a,C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,c)]);return R};ye.decryptPrivateKeyInfo=function(r,e){var t=null,n={},i=[];if(!C.validate(r,GO,n,i)){var s=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=C.derToOid(n.encryptionOid),a=ye.pbe.getCipher(o,n.encryptionParams,e),c=H.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(t=C.fromDer(a.output)),t};ye.encryptedPrivateKeyToPem=function(r,e){var t={type:"ENCRYPTED PRIVATE KEY",body:C.toDer(r).getBytes()};return H.pem.encode(t,{maxline:e})};ye.encryptedPrivateKeyFromPem=function(r){var e=H.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 C.fromDer(e.body)};ye.encryptRsaPrivateKey=function(r,e,t){if(t=t||{},!t.legacy){var n=ye.wrapRsaPrivateKey(ye.privateKeyToAsn1(r));return n=ye.encryptPrivateKeyInfo(n,e,t),ye.encryptedPrivateKeyToPem(n)}var i,s,o,a;switch(t.algorithm){case"aes128":i="AES-128-CBC",o=16,s=H.random.getBytesSync(16),a=H.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",o=24,s=H.random.getBytesSync(16),a=H.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",o=32,s=H.random.getBytesSync(16),a=H.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",o=24,s=H.random.getBytesSync(8),a=H.des.createEncryptionCipher;break;case"des":i="DES-CBC",o=8,s=H.random.getBytesSync(8),a=H.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=H.pbe.opensslDeriveBytes(e,s.substr(0,8),o),l=a(u);l.start(s),l.update(C.toDer(ye.privateKeyToAsn1(r))),l.finish();var h={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:H.util.bytesToHex(s).toUpperCase()},body:l.output.getBytes()};return H.pem.encode(h)};ye.decryptRsaPrivateKey=function(r,e){var t=null,n=H.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 s,o;switch(n.dekInfo.algorithm){case"DES-CBC":s=8,o=H.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,o=H.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,o=H.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,o=H.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,o=H.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,o=function(h){return H.rc2.createDecryptionCipher(h,40)};break;case"RC2-64-CBC":s=8,o=function(h){return H.rc2.createDecryptionCipher(h,64)};break;case"RC2-128-CBC":s=16,o=function(h){return H.rc2.createDecryptionCipher(h,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=H.util.hexToBytes(n.dekInfo.parameters),c=H.pbe.opensslDeriveBytes(e,a.substr(0,8),s),u=o(c);if(u.start(a),u.update(H.util.createBuffer(n.body)),u.finish())t=u.output.getBytes();else return t}else t=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?t=ye.decryptPrivateKeyInfo(C.fromDer(t),e):t=C.fromDer(t),t!==null&&(t=ye.privateKeyFromAsn1(t)),t};ye.pbe.generatePkcs12Key=function(r,e,t,n,i,s){var o,a;if(typeof s>"u"||s===null){if(!("sha1"in H.md))throw new Error('"sha1" hash algorithm unavailable.');s=H.md.sha1.create()}var c=s.digestLength,u=s.blockLength,l=new H.util.ByteBuffer,h=new H.util.ByteBuffer;if(r!=null){for(a=0;a<r.length;a++)h.putInt16(r.charCodeAt(a));h.putInt16(0)}var f=h.length(),d=e.length(),p=new H.util.ByteBuffer;p.fillWithByte(t,u);var m=u*Math.ceil(d/u),g=new H.util.ByteBuffer;for(a=0;a<m;a++)g.putByte(e.at(a%d));var y=u*Math.ceil(f/u),b=new H.util.ByteBuffer;for(a=0;a<y;a++)b.putByte(h.at(a%f));var E=g;E.putBuffer(b);for(var R=Math.ceil(i/c),v=1;v<=R;v++){var _=new H.util.ByteBuffer;_.putBytes(p.bytes()),_.putBytes(E.bytes());for(var I=0;I<n;I++)s.start(),s.update(_.getBytes()),_=s.digest();var P=new H.util.ByteBuffer;for(a=0;a<u;a++)P.putByte(_.at(a%c));var M=Math.ceil(d/u)+Math.ceil(f/u),W=new H.util.ByteBuffer;for(o=0;o<M;o++){var ue=new H.util.ByteBuffer(E.getBytes(u)),le=511;for(a=P.length()-1;a>=0;a--)le=le>>8,le+=P.at(a)+ue.at(a),ue.setAt(a,le&255);W.putBuffer(ue)}E=W,l.putBuffer(_)}return l.truncate(l.length()-i),l};ye.pbe.getCipher=function(r,e,t){switch(r){case ye.oids.pkcs5PBES2:return ye.pbe.getCipherForPBES2(r,e,t);case ye.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case ye.oids["pbewithSHAAnd40BitRC2-CBC"]:return ye.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}};ye.pbe.getCipherForPBES2=function(r,e,t){var n={},i=[];if(!C.validate(e,WO,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(r=C.derToOid(n.kdfOid),r!==ye.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=r,s.supportedOids=["pkcs5PBKDF2"],s}if(r=C.derToOid(n.encOid),r!==ye.oids["aes128-CBC"]&&r!==ye.oids["aes192-CBC"]&&r!==ye.oids["aes256-CBC"]&&r!==ye.oids["des-EDE3-CBC"]&&r!==ye.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=r,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var o=n.kdfSalt,a=H.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(ye.oids[r]){case"aes128-CBC":c=16,u=H.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=H.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=H.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=H.des.createDecryptionCipher;break;case"desCBC":c=8,u=H.des.createDecryptionCipher;break}var l=ab(n.prfOid),h=H.pkcs5.pbkdf2(t,o,a,c,l),f=n.encIv,d=u(h);return d.start(f),d};ye.pbe.getCipherForPKCS12PBE=function(r,e,t){var n={},i=[];if(!C.validate(e,YO,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var o=H.util.createBuffer(n.salt),a=H.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(r){case ye.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=H.des.startDecrypting;break;case ye.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(m,g){var y=H.rc2.createDecryptionCipher(m,40);return y.start(g,null),y};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=r,s}var h=ab(n.prfOid),f=ye.pbe.generatePkcs12Key(t,o,1,a,c,h);h.start();var d=ye.pbe.generatePkcs12Key(t,o,2,a,u,h);return l(f,d)};ye.pbe.opensslDeriveBytes=function(r,e,t,n){if(typeof n>"u"||n===null){if(!("md5"in H.md))throw new Error('"md5" hash algorithm unavailable.');n=H.md.md5.create()}e===null&&(e="");for(var i=[ob(n,r+e)],s=16,o=1;s<t;++o,s+=16)i.push(ob(n,i[o-1]+r+e));return i.join("").substr(0,t)};function ob(r,e){return r.start().update(e).digest().getBytes()}function ab(r){var e;if(!r)e="hmacWithSHA1";else if(e=ye.oids[C.derToOid(r)],!e){var t=new Error("Unsupported PRF OID.");throw t.oid=r,t.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],t}return cb(e)}function cb(r){var e=H.md;switch(r){case"hmacWithSHA224":e=H.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":r=r.substr(8).toLowerCase();break;default:var t=new Error("Unsupported PRF algorithm.");throw t.algorithm=r,t.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],t}if(!e||!(r in e))throw new Error("Unknown hash algorithm: "+r);return e[r].create()}function QO(r,e,t,n){var i=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,r),C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,e.getBytes())]);return n!=="hmacWithSHA1"&&i.value.push(C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,H.util.hexToBytes(t.toString(16))),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(ye.oids[n]).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.NULL,!1,"")])),i}});var Vb=T((Zte,qb)=>{var gt=rt();Co();Ft();var Qu=qb.exports=gt.sha512=gt.sha512||{};gt.md.sha512=gt.md.algorithms.sha512=Qu;var Fb=gt.sha384=gt.sha512.sha384=gt.sha512.sha384||{};Fb.create=function(){return Qu.create("SHA-384")};gt.md.sha384=gt.md.algorithms.sha384=Fb;gt.sha512.sha256=gt.sha512.sha256||{create:function(){return Qu.create("SHA-512/256")}};gt.md["sha512/256"]=gt.md.algorithms["sha512/256"]=gt.sha512.sha256;gt.sha512.sha224=gt.sha512.sha224||{create:function(){return Qu.create("SHA-512/224")}};gt.md["sha512/224"]=gt.md.algorithms["sha512/224"]=gt.sha512.sha224;Qu.create=function(r){if(Kb||xB(),typeof r>"u"&&(r="SHA-512"),!(r in Bo))throw new Error("Invalid SHA-512 algorithm: "+r);for(var e=Bo[r],t=null,n=gt.util.createBuffer(),i=new Array(80),s=0;s<80;++s)i[s]=new Array(2);var o=64;switch(r){case"SHA-384":o=48;break;case"SHA-512/256":o=32;break;case"SHA-512/224":o=28;break}var a={algorithm:r.replace("-","").toLowerCase(),blockLength:128,digestLength:o,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<c;++u)a.fullMessageLength.push(0);n=gt.util.createBuffer(),t=new Array(e.length);for(var u=0;u<e.length;++u)t[u]=e[u].slice(0);return a},a.start(),a.update=function(c,u){u==="utf8"&&(c=gt.util.encodeUtf8(c));var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var h=a.fullMessageLength.length-1;h>=0;--h)a.fullMessageLength[h]+=l[1],l[1]=l[0]+(a.fullMessageLength[h]/4294967296>>>0),a.fullMessageLength[h]=a.fullMessageLength[h]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),Ub(t,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=gt.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(M3.substr(0,a.blockLength-l));for(var h,f,d=a.fullMessageLength[0]*8,p=0;p<a.fullMessageLength.length-1;++p)h=a.fullMessageLength[p+1]*8,f=h/4294967296>>>0,d+=f,c.putInt32(d>>>0),d=h>>>0;c.putInt32(d);for(var m=new Array(t.length),p=0;p<t.length;++p)m[p]=t[p].slice(0);Ub(m,i,c);var g=gt.util.createBuffer(),y;r==="SHA-512"?y=m.length:r==="SHA-384"?y=m.length-2:y=m.length-4;for(var p=0;p<y;++p)g.putInt32(m[p][0]),(p!==y-1||r!=="SHA-512/224")&&g.putInt32(m[p][1]);return g},a};var M3=null,Kb=!1,U3=null,Bo=null;function xB(){M3=String.fromCharCode(128),M3+=gt.util.fillString(String.fromCharCode(0),128),U3=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],Bo={},Bo["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],Bo["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],Bo["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],Bo["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],Kb=!0}function Ub(r,e,t){for(var n,i,s,o,a,c,u,l,h,f,d,p,m,g,y,b,E,R,v,_,I,P,M,W,ue,le,Ce,Ve,ae,de,k,fe,ut,_e,Se,Re=t.length();Re>=128;){for(ae=0;ae<16;++ae)e[ae][0]=t.getInt32()>>>0,e[ae][1]=t.getInt32()>>>0;for(;ae<80;++ae)fe=e[ae-2],de=fe[0],k=fe[1],n=((de>>>19|k<<13)^(k>>>29|de<<3)^de>>>6)>>>0,i=((de<<13|k>>>19)^(k<<3|de>>>29)^(de<<26|k>>>6))>>>0,_e=e[ae-15],de=_e[0],k=_e[1],s=((de>>>1|k<<31)^(de>>>8|k<<24)^de>>>7)>>>0,o=((de<<31|k>>>1)^(de<<24|k>>>8)^(de<<25|k>>>7))>>>0,ut=e[ae-7],Se=e[ae-16],k=i+ut[1]+o+Se[1],e[ae][0]=n+ut[0]+s+Se[0]+(k/4294967296>>>0)>>>0,e[ae][1]=k>>>0;for(m=r[0][0],g=r[0][1],y=r[1][0],b=r[1][1],E=r[2][0],R=r[2][1],v=r[3][0],_=r[3][1],I=r[4][0],P=r[4][1],M=r[5][0],W=r[5][1],ue=r[6][0],le=r[6][1],Ce=r[7][0],Ve=r[7][1],ae=0;ae<80;++ae)u=((I>>>14|P<<18)^(I>>>18|P<<14)^(P>>>9|I<<23))>>>0,l=((I<<18|P>>>14)^(I<<14|P>>>18)^(P<<23|I>>>9))>>>0,h=(ue^I&(M^ue))>>>0,f=(le^P&(W^le))>>>0,a=((m>>>28|g<<4)^(g>>>2|m<<30)^(g>>>7|m<<25))>>>0,c=((m<<4|g>>>28)^(g<<30|m>>>2)^(g<<25|m>>>7))>>>0,d=(m&y|E&(m^y))>>>0,p=(g&b|R&(g^b))>>>0,k=Ve+l+f+U3[ae][1]+e[ae][1],n=Ce+u+h+U3[ae][0]+e[ae][0]+(k/4294967296>>>0)>>>0,i=k>>>0,k=c+p,s=a+d+(k/4294967296>>>0)>>>0,o=k>>>0,Ce=ue,Ve=le,ue=M,le=W,M=I,W=P,k=_+i,I=v+n+(k/4294967296>>>0)>>>0,P=k>>>0,v=E,_=R,E=y,R=b,y=m,b=g,k=i+o,m=n+s+(k/4294967296>>>0)>>>0,g=k>>>0;k=r[0][1]+g,r[0][0]=r[0][0]+m+(k/4294967296>>>0)>>>0,r[0][1]=k>>>0,k=r[1][1]+b,r[1][0]=r[1][0]+y+(k/4294967296>>>0)>>>0,r[1][1]=k>>>0,k=r[2][1]+R,r[2][0]=r[2][0]+E+(k/4294967296>>>0)>>>0,r[2][1]=k>>>0,k=r[3][1]+_,r[3][0]=r[3][0]+v+(k/4294967296>>>0)>>>0,r[3][1]=k>>>0,k=r[4][1]+P,r[4][0]=r[4][0]+I+(k/4294967296>>>0)>>>0,r[4][1]=k>>>0,k=r[5][1]+W,r[5][0]=r[5][0]+M+(k/4294967296>>>0)>>>0,r[5][1]=k>>>0,k=r[6][1]+le,r[6][0]=r[6][0]+ue+(k/4294967296>>>0)>>>0,r[6][1]=k>>>0,k=r[7][1]+Ve,r[7][0]=r[7][0]+Ce+(k/4294967296>>>0)>>>0,r[7][1]=k>>>0,Re-=128}}});var AE=T((nne,SE)=>{"use strict";function kt(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)}kt.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]}};kt.prototype.get=function(e){return this.peekAt(e)};kt.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};kt.prototype.peekFront=function(){return this.peek()};kt.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(kt.prototype,"length",{get:function(){return this.size()}});kt.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};kt.prototype.unshift=function(e){if(e===void 0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};kt.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};kt.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._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};kt.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}};kt.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 s=this._list[t],o;if(e<n/2){for(o=e;o>0;o--)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(o=n-1-e;o>0;o--)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 s}}};kt.prototype.remove=function(e,t){var n=e,i,s=t;if(n===(n|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(n>=o||n<-o||t<1)){if(n<0&&(n+=o),t===1||!t)return i=new Array(1),i[0]=this.removeOne(n),i;if(n===0&&n+t>=o)return i=this.toArray(),this.clear(),i;n+t>o&&(t=o-n);var c;for(i=new Array(t),c=0;c<t;c++)i[c]=this._list[this._head+n+c&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;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(n<o/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;s>0;)this._list[n=n-1+a&this._capacityMask]=void 0,s--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=o-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+a&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),i}}};kt.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 s,o,a,c=arguments.length,u=this._list.length,l=2;if(!i||n<i/2){for(o=new Array(n),s=0;s<n;s++)o[s]=this._list[this._head+s&this._capacityMask];for(t===0?(a=[],n>0&&(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(s=n;s>0;s--)this.unshift(o[s-1])}else{o=new Array(i-(n+t));var h=o.length;for(s=0;s<h;s++)o[s]=this._list[this._head+n+t+s&this._capacityMask];for(t===0?(a=[],n!=i&&(this._tail=this._head+n+u&this._capacityMask)):(a=this.remove(n,t),this._tail=this._tail-h+u&this._capacityMask);l<c;)this.push(arguments[l++]);for(s=0;s<h;s++)this.push(o[s])}return a}else return this.remove(n,t)}};kt.prototype.clear=function(){this._head=0,this._tail=0};kt.prototype.isEmpty=function(){return this._head===this._tail};kt.prototype.toArray=function(){return this._copyArray(!1)};kt.prototype._fromArray=function(e){for(var t=0;t<e.length;t++)this.push(e[t])};kt.prototype._copyArray=function(e){var t=[],n=this._list,i=n.length,s;if(e||this._head>this._tail){for(s=this._head;s<i;s++)t.push(n[s]);for(s=0;s<this._tail;s++)t.push(n[s])}else for(s=this._head;s<this._tail;s++)t.push(n[s]);return t};kt.prototype._growArray=function(){this._head&&(this._list=this._copyArray(!0),this._head=0),this._tail=this._list.length,this._list.length<<=1,this._capacityMask=this._capacityMask<<1|1};kt.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};SE.exports=kt});var lv=T(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});function vU(r,e){var t=r>>>16&65535,n=r&65535,i=e>>>16&65535,s=e&65535;return n*s+(t*s+n*i<<16>>>0)|0}hn.mul=Math.imul||vU;function xU(r,e){return r+e|0}hn.add=xU;function _U(r,e){return r-e|0}hn.sub=_U;function SU(r,e){return r<<e|r>>>32-e}hn.rotl=SU;function AU(r,e){return r<<32-e|r>>>e}hn.rotr=AU;function RU(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r}hn.isInteger=Number.isInteger||RU;hn.MAX_SAFE_INTEGER=9007199254740991;hn.isSafeInteger=function(r){return hn.isInteger(r)&&r>=-hn.MAX_SAFE_INTEGER&&r<=hn.MAX_SAFE_INTEGER}});var al=T(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});var hv=lv();function IU(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}Ee.readInt16BE=IU;function TU(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}Ee.readUint16BE=TU;function DU(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}Ee.readInt16LE=DU;function CU(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}Ee.readUint16LE=CU;function fv(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}Ee.writeUint16BE=fv;Ee.writeInt16BE=fv;function dv(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}Ee.writeUint16LE=dv;Ee.writeInt16LE=dv;function dm(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}Ee.readInt32BE=dm;function pm(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}Ee.readUint32BE=pm;function mm(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}Ee.readInt32LE=mm;function gm(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}Ee.readUint32LE=gm;function y0(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}Ee.writeUint32BE=y0;Ee.writeInt32BE=y0;function w0(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}Ee.writeUint32LE=w0;Ee.writeInt32LE=w0;function PU(r,e){e===void 0&&(e=0);var t=dm(r,e),n=dm(r,e+4);return t*4294967296+n-(n>>31)*4294967296}Ee.readInt64BE=PU;function kU(r,e){e===void 0&&(e=0);var t=pm(r,e),n=pm(r,e+4);return t*4294967296+n}Ee.readUint64BE=kU;function NU(r,e){e===void 0&&(e=0);var t=mm(r,e),n=mm(r,e+4);return n*4294967296+t-(t>>31)*4294967296}Ee.readInt64LE=NU;function LU(r,e){e===void 0&&(e=0);var t=gm(r,e),n=gm(r,e+4);return n*4294967296+t}Ee.readUint64LE=LU;function pv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),y0(r/4294967296>>>0,e,t),y0(r>>>0,e,t+4),e}Ee.writeUint64BE=pv;Ee.writeInt64BE=pv;function mv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),w0(r>>>0,e,t),w0(r/4294967296>>>0,e,t+4),e}Ee.writeUint64LE=mv;Ee.writeInt64LE=mv;function OU(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,s=r/8+t-1;s>=t;s--)n+=e[s]*i,i*=256;return n}Ee.readUintBE=OU;function BU(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,s=t;s<t+r/8;s++)n+=e[s]*i,i*=256;return n}Ee.readUintLE=BU;function MU(r,e,t,n){if(t===void 0&&(t=new Uint8Array(r/8)),n===void 0&&(n=0),r%8!==0)throw new Error("writeUintBE supports only bitLengths divisible by 8");if(!hv.isSafeInteger(e))throw new Error("writeUintBE value must be an integer");for(var i=1,s=r/8+n-1;s>=n;s--)t[s]=e/i&255,i*=256;return t}Ee.writeUintBE=MU;function UU(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(!hv.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s<n+r/8;s++)t[s]=e/i&255,i*=256;return t}Ee.writeUintLE=UU;function FU(r,e){e===void 0&&(e=0);var t=new DataView(r.buffer,r.byteOffset,r.byteLength);return t.getFloat32(e)}Ee.readFloat32BE=FU;function KU(r,e){e===void 0&&(e=0);var t=new DataView(r.buffer,r.byteOffset,r.byteLength);return t.getFloat32(e,!0)}Ee.readFloat32LE=KU;function qU(r,e){e===void 0&&(e=0);var t=new DataView(r.buffer,r.byteOffset,r.byteLength);return t.getFloat64(e)}Ee.readFloat64BE=qU;function VU(r,e){e===void 0&&(e=0);var t=new DataView(r.buffer,r.byteOffset,r.byteLength);return t.getFloat64(e,!0)}Ee.readFloat64LE=VU;function zU(r,e,t){e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0);var n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setFloat32(t,r),e}Ee.writeFloat32BE=zU;function HU(r,e,t){e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0);var n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setFloat32(t,r,!0),e}Ee.writeFloat32LE=HU;function $U(r,e,t){e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0);var n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setFloat64(t,r),e}Ee.writeFloat64BE=$U;function GU(r,e,t){e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0);var n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setFloat64(t,r,!0),e}Ee.writeFloat64LE=GU});var Di=T(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});function WU(r){for(var e=0;e<r.length;e++)r[e]=0;return r}ym.wipe=WU});var yv=T(b0=>{"use strict";Object.defineProperty(b0,"__esModule",{value:!0});var Sr=al(),wm=Di(),YU=20;function QU(r,e,t){for(var n=1634760805,i=857760878,s=2036477234,o=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],h=t[19]<<24|t[18]<<16|t[17]<<8|t[16],f=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],m=e[3]<<24|e[2]<<16|e[1]<<8|e[0],g=e[7]<<24|e[6]<<16|e[5]<<8|e[4],y=e[11]<<24|e[10]<<16|e[9]<<8|e[8],b=e[15]<<24|e[14]<<16|e[13]<<8|e[12],E=n,R=i,v=s,_=o,I=a,P=c,M=u,W=l,ue=h,le=f,Ce=d,Ve=p,ae=m,de=g,k=y,fe=b,ut=0;ut<YU;ut+=2)E=E+I|0,ae^=E,ae=ae>>>32-16|ae<<16,ue=ue+ae|0,I^=ue,I=I>>>32-12|I<<12,R=R+P|0,de^=R,de=de>>>32-16|de<<16,le=le+de|0,P^=le,P=P>>>32-12|P<<12,v=v+M|0,k^=v,k=k>>>32-16|k<<16,Ce=Ce+k|0,M^=Ce,M=M>>>32-12|M<<12,_=_+W|0,fe^=_,fe=fe>>>32-16|fe<<16,Ve=Ve+fe|0,W^=Ve,W=W>>>32-12|W<<12,v=v+M|0,k^=v,k=k>>>32-8|k<<8,Ce=Ce+k|0,M^=Ce,M=M>>>32-7|M<<7,_=_+W|0,fe^=_,fe=fe>>>32-8|fe<<8,Ve=Ve+fe|0,W^=Ve,W=W>>>32-7|W<<7,R=R+P|0,de^=R,de=de>>>32-8|de<<8,le=le+de|0,P^=le,P=P>>>32-7|P<<7,E=E+I|0,ae^=E,ae=ae>>>32-8|ae<<8,ue=ue+ae|0,I^=ue,I=I>>>32-7|I<<7,E=E+P|0,fe^=E,fe=fe>>>32-16|fe<<16,Ce=Ce+fe|0,P^=Ce,P=P>>>32-12|P<<12,R=R+M|0,ae^=R,ae=ae>>>32-16|ae<<16,Ve=Ve+ae|0,M^=Ve,M=M>>>32-12|M<<12,v=v+W|0,de^=v,de=de>>>32-16|de<<16,ue=ue+de|0,W^=ue,W=W>>>32-12|W<<12,_=_+I|0,k^=_,k=k>>>32-16|k<<16,le=le+k|0,I^=le,I=I>>>32-12|I<<12,v=v+W|0,de^=v,de=de>>>32-8|de<<8,ue=ue+de|0,W^=ue,W=W>>>32-7|W<<7,_=_+I|0,k^=_,k=k>>>32-8|k<<8,le=le+k|0,I^=le,I=I>>>32-7|I<<7,R=R+M|0,ae^=R,ae=ae>>>32-8|ae<<8,Ve=Ve+ae|0,M^=Ve,M=M>>>32-7|M<<7,E=E+P|0,fe^=E,fe=fe>>>32-8|fe<<8,Ce=Ce+fe|0,P^=Ce,P=P>>>32-7|P<<7;Sr.writeUint32LE(E+n|0,r,0),Sr.writeUint32LE(R+i|0,r,4),Sr.writeUint32LE(v+s|0,r,8),Sr.writeUint32LE(_+o|0,r,12),Sr.writeUint32LE(I+a|0,r,16),Sr.writeUint32LE(P+c|0,r,20),Sr.writeUint32LE(M+u|0,r,24),Sr.writeUint32LE(W+l|0,r,28),Sr.writeUint32LE(ue+h|0,r,32),Sr.writeUint32LE(le+f|0,r,36),Sr.writeUint32LE(Ce+d|0,r,40),Sr.writeUint32LE(Ve+p|0,r,44),Sr.writeUint32LE(ae+m|0,r,48),Sr.writeUint32LE(de+g|0,r,52),Sr.writeUint32LE(k+y|0,r,56),Sr.writeUint32LE(fe+b|0,r,60)}function gv(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<t.length)throw new Error("ChaCha: destination is shorter than source");var s,o;if(i===0){if(e.length!==8&&e.length!==12)throw new Error("ChaCha nonce must be 8 or 12 bytes");s=new Uint8Array(16),o=s.length-e.length,s.set(e,o)}else{if(e.length!==16)throw new Error("ChaCha nonce with counter must be 16 bytes");s=e,o=i}for(var a=new Uint8Array(64),c=0;c<t.length;c+=64){QU(a,s,r);for(var u=c;u<c+64&&u<t.length;u++)n[u]=t[u]^a[u-c];jU(s,0,o)}return wm.wipe(a),i===0&&wm.wipe(s),n}b0.streamXOR=gv;function XU(r,e,t,n){return n===void 0&&(n=0),wm.wipe(t),gv(r,e,t,t,n)}b0.stream=XU;function jU(r,e,t){for(var n=1;t--;)n=n+(r[e]&255)|0,r[e]=n&255,n>>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var E0=T(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});function ZU(r,e,t){return~(r-1)&e|r-1&t}ac.select=ZU;function JU(r,e){return(r|0)-(e|0)-1>>>31&1}ac.lessOrEqual=JU;function wv(r,e){if(r.length!==e.length)return 0;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return 1&t-1>>>8}ac.compare=wv;function eF(r,e){return r.length===0||e.length===0?!1:wv(r,e)!==0}ac.equal=eF});var Ev=T(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var tF=E0(),v0=Di();ts.DIGEST_LENGTH=16;var bv=function(){function r(e){this.digestLength=ts.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 s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=(o>>>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,s=this._h[0],o=this._h[1],a=this._h[2],c=this._h[3],u=this._h[4],l=this._h[5],h=this._h[6],f=this._h[7],d=this._h[8],p=this._h[9],m=this._r[0],g=this._r[1],y=this._r[2],b=this._r[3],E=this._r[4],R=this._r[5],v=this._r[6],_=this._r[7],I=this._r[8],P=this._r[9];n>=16;){var M=e[t+0]|e[t+1]<<8;s+=M&8191;var W=e[t+2]|e[t+3]<<8;o+=(M>>>13|W<<3)&8191;var ue=e[t+4]|e[t+5]<<8;a+=(W>>>10|ue<<6)&8191;var le=e[t+6]|e[t+7]<<8;c+=(ue>>>7|le<<9)&8191;var Ce=e[t+8]|e[t+9]<<8;u+=(le>>>4|Ce<<12)&8191,l+=Ce>>>1&8191;var Ve=e[t+10]|e[t+11]<<8;h+=(Ce>>>14|Ve<<2)&8191;var ae=e[t+12]|e[t+13]<<8;f+=(Ve>>>11|ae<<5)&8191;var de=e[t+14]|e[t+15]<<8;d+=(ae>>>8|de<<8)&8191,p+=de>>>5|i;var k=0,fe=k;fe+=s*m,fe+=o*(5*P),fe+=a*(5*I),fe+=c*(5*_),fe+=u*(5*v),k=fe>>>13,fe&=8191,fe+=l*(5*R),fe+=h*(5*E),fe+=f*(5*b),fe+=d*(5*y),fe+=p*(5*g),k+=fe>>>13,fe&=8191;var ut=k;ut+=s*g,ut+=o*m,ut+=a*(5*P),ut+=c*(5*I),ut+=u*(5*_),k=ut>>>13,ut&=8191,ut+=l*(5*v),ut+=h*(5*R),ut+=f*(5*E),ut+=d*(5*b),ut+=p*(5*y),k+=ut>>>13,ut&=8191;var _e=k;_e+=s*y,_e+=o*g,_e+=a*m,_e+=c*(5*P),_e+=u*(5*I),k=_e>>>13,_e&=8191,_e+=l*(5*_),_e+=h*(5*v),_e+=f*(5*R),_e+=d*(5*E),_e+=p*(5*b),k+=_e>>>13,_e&=8191;var Se=k;Se+=s*b,Se+=o*y,Se+=a*g,Se+=c*m,Se+=u*(5*P),k=Se>>>13,Se&=8191,Se+=l*(5*I),Se+=h*(5*_),Se+=f*(5*v),Se+=d*(5*R),Se+=p*(5*E),k+=Se>>>13,Se&=8191;var Re=k;Re+=s*E,Re+=o*b,Re+=a*y,Re+=c*g,Re+=u*m,k=Re>>>13,Re&=8191,Re+=l*(5*P),Re+=h*(5*I),Re+=f*(5*_),Re+=d*(5*v),Re+=p*(5*R),k+=Re>>>13,Re&=8191;var ze=k;ze+=s*R,ze+=o*E,ze+=a*b,ze+=c*y,ze+=u*g,k=ze>>>13,ze&=8191,ze+=l*m,ze+=h*(5*P),ze+=f*(5*I),ze+=d*(5*_),ze+=p*(5*v),k+=ze>>>13,ze&=8191;var He=k;He+=s*v,He+=o*R,He+=a*E,He+=c*b,He+=u*y,k=He>>>13,He&=8191,He+=l*g,He+=h*m,He+=f*(5*P),He+=d*(5*I),He+=p*(5*_),k+=He>>>13,He&=8191;var $e=k;$e+=s*_,$e+=o*v,$e+=a*R,$e+=c*E,$e+=u*b,k=$e>>>13,$e&=8191,$e+=l*y,$e+=h*g,$e+=f*m,$e+=d*(5*P),$e+=p*(5*I),k+=$e>>>13,$e&=8191;var Ge=k;Ge+=s*I,Ge+=o*_,Ge+=a*v,Ge+=c*R,Ge+=u*E,k=Ge>>>13,Ge&=8191,Ge+=l*b,Ge+=h*y,Ge+=f*g,Ge+=d*m,Ge+=p*(5*P),k+=Ge>>>13,Ge&=8191;var We=k;We+=s*P,We+=o*I,We+=a*_,We+=c*v,We+=u*R,k=We>>>13,We&=8191,We+=l*E,We+=h*b,We+=f*y,We+=d*g,We+=p*m,k+=We>>>13,We&=8191,k=(k<<2)+k|0,k=k+fe|0,fe=k&8191,k=k>>>13,ut+=k,s=fe,o=ut,a=_e,c=Se,u=Re,l=ze,h=He,f=$e,d=Ge,p=We,t+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=a,this._h[3]=c,this._h[4]=u,this._h[5]=l,this._h[6]=h,this._h[7]=f,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,s,o,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,s=(i^1)-1,a=0;a<10;a++)n[a]&=s;for(s=~s,a=0;a<10;a++)this._h[a]=this._h[a]&s|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,o=this._h[0]+this._pad[0],this._h[0]=o&65535,a=1;a<8;a++)o=(this._h[a]+this._pad[a]|0)+(o>>>16)|0,this._h[a]=o&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 s=0;s<i;s++)this._buffer[this._leftover+s]=e[t+s];if(n-=i,t+=i,this._leftover+=i,this._leftover<16)return this;this._blocks(this._buffer,0,16),this._leftover=0}if(n>=16&&(i=n-n%16,this._blocks(e,t,i),t+=i,n-=i),n){for(var s=0;s<n;s++)this._buffer[this._leftover+s]=e[t+s];this._leftover+=n}return this},r.prototype.digest=function(){if(this._finished)throw new Error("Poly1305 was finished");var e=new Uint8Array(16);return this.finish(e),e},r.prototype.clean=function(){return v0.wipe(this._buffer),v0.wipe(this._r),v0.wipe(this._h),v0.wipe(this._pad),this._leftover=0,this._fin=0,this._finished=!0,this},r}();ts.Poly1305=bv;function rF(r,e){var t=new bv(r);t.update(e);var n=t.digest();return t.clean(),n}ts.oneTimeAuth=rF;function nF(r,e){return r.length!==ts.DIGEST_LENGTH||e.length!==ts.DIGEST_LENGTH?!1:tF.equal(r,e)}ts.equal=nF});var ul=T(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var x0=yv(),iF=Ev(),cl=Di(),vv=al(),sF=E0();rs.KEY_LENGTH=32;rs.NONCE_LENGTH=12;rs.TAG_LENGTH=16;var xv=new Uint8Array(16),oF=function(){function r(e){if(this.nonceLength=rs.NONCE_LENGTH,this.tagLength=rs.TAG_LENGTH,e.length!==rs.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 s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);x0.stream(this._key,s,o,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 x0.streamXOR(this._key,s,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),o,c.subarray(0,c.length-this.tagLength),n),cl.wipe(s),c},r.prototype.open=function(e,t,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length<this.tagLength)return null;var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);x0.stream(this._key,s,o,4);var a=new Uint8Array(this.tagLength);if(this._authenticate(a,o,t.subarray(0,t.length-this.tagLength),n),!sF.equal(a,t.subarray(t.length-this.tagLength,t.length)))return null;var c=t.length-this.tagLength,u;if(i){if(i.length!==c)throw new Error("ChaCha20Poly1305: incorrect destination length");u=i}else u=new Uint8Array(c);return x0.streamXOR(this._key,s,t.subarray(0,t.length-this.tagLength),u,4),cl.wipe(s),u},r.prototype.clean=function(){return cl.wipe(this._key),this},r.prototype._authenticate=function(e,t,n,i){var s=new iF.Poly1305(t);i&&(s.update(i),i.length%16>0&&s.update(xv.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(xv.subarray(n.length%16));var o=new Uint8Array(8);i&&vv.writeUint64LE(i.length,o),s.update(o),vv.writeUint64LE(n.length,o),s.update(o);for(var a=s.digest(),c=0;c<a.length;c++)e[c]=a[c];s.clean(),cl.wipe(a),cl.wipe(o)},r}();rs.ChaCha20Poly1305=oF});var Sv=T(_0=>{"use strict";Object.defineProperty(_0,"__esModule",{value:!0});_0.BrowserRandomSource=void 0;var _v=65536,bm=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<t.length;n+=_v)this._crypto.getRandomValues(t.subarray(n,n+Math.min(t.length-n,_v)));return t}};_0.BrowserRandomSource=bm});var Av=T(S0=>{"use strict";Object.defineProperty(S0,"__esModule",{value:!0});S0.NodeRandomSource=void 0;var aF=Di(),Em=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof sh<"u"){let e=Ns();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<n.length;i++)n[i]=t[i];return(0,aF.wipe)(t),n}};S0.NodeRandomSource=Em});var Rv=T(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});A0.SystemRandomSource=void 0;var cF=Sv(),uF=Av(),vm=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new cF.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new uF.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)}};A0.SystemRandomSource=vm});var Cv=T(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.randomStringForEntropy=Ar.randomString=Ar.randomUint32=Ar.randomBytes=Ar.defaultRandomSource=void 0;var lF=Rv(),hF=al(),Iv=Di();Ar.defaultRandomSource=new lF.SystemRandomSource;function xm(r,e=Ar.defaultRandomSource){return e.randomBytes(r)}Ar.randomBytes=xm;function fF(r=Ar.defaultRandomSource){let e=xm(4,r),t=(0,hF.readUint32LE)(e);return(0,Iv.wipe)(e),t}Ar.randomUint32=fF;var Tv="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Dv(r,e=Tv,t=Ar.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,s=256-256%i;for(;r>0;){let o=xm(Math.ceil(r*256/s),t);for(let a=0;a<o.length&&r>0;a++){let c=o[a];c<s&&(n+=e.charAt(c%i),r--)}(0,Iv.wipe)(o)}return n}Ar.randomString=Dv;function dF(r,e=Tv,t=Ar.defaultRandomSource){let n=Math.ceil(r/(Math.log(e.length)/Math.LN2));return Dv(n,e,t)}Ar.randomStringForEntropy=dF});var Am=T(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.sharedKey=Nt.generateKeyPair=Nt.generateKeyPairFromSeed=Nt.scalarMultBase=Nt.scalarMult=Nt.SHARED_KEY_LENGTH=Nt.SECRET_KEY_LENGTH=Nt.PUBLIC_KEY_LENGTH=void 0;var pF=Cv(),mF=Di();Nt.PUBLIC_KEY_LENGTH=32;Nt.SECRET_KEY_LENGTH=32;Nt.SHARED_KEY_LENGTH=32;function Ci(r){let e=new Float64Array(16);if(r)for(let t=0;t<r.length;t++)e[t]=r[t];return e}var Pv=new Uint8Array(32);Pv[0]=9;var gF=Ci([56129,1]);function _m(r){let e=1;for(let t=0;t<16;t++){let n=r[t]+e+65535;e=Math.floor(n/65536),r[t]=n-e*65536}r[0]+=e-1+37*(e-1)}function ll(r,e,t){let n=~(t-1);for(let i=0;i<16;i++){let s=n&(r[i]^e[i]);r[i]^=s,e[i]^=s}}function yF(r,e){let t=Ci(),n=Ci();for(let i=0;i<16;i++)n[i]=e[i];_m(n),_m(n),_m(n);for(let i=0;i<2;i++){t[0]=n[0]-65517;for(let o=1;o<15;o++)t[o]=n[o]-65535-(t[o-1]>>16&1),t[o-1]&=65535;t[15]=n[15]-32767-(t[14]>>16&1);let s=t[15]>>16&1;t[14]&=65535,ll(n,t,1-s)}for(let i=0;i<16;i++)r[2*i]=n[i]&255,r[2*i+1]=n[i]>>8}function wF(r,e){for(let t=0;t<16;t++)r[t]=e[2*t]+(e[2*t+1]<<8);r[15]&=32767}function R0(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]+t[n]}function I0(r,e,t){for(let n=0;n<16;n++)r[n]=e[n]-t[n]}function ns(r,e,t){let n,i,s=0,o=0,a=0,c=0,u=0,l=0,h=0,f=0,d=0,p=0,m=0,g=0,y=0,b=0,E=0,R=0,v=0,_=0,I=0,P=0,M=0,W=0,ue=0,le=0,Ce=0,Ve=0,ae=0,de=0,k=0,fe=0,ut=0,_e=t[0],Se=t[1],Re=t[2],ze=t[3],He=t[4],$e=t[5],Ge=t[6],We=t[7],hr=t[8],fr=t[9],dr=t[10],pr=t[11],mr=t[12],gr=t[13],yr=t[14],wr=t[15];n=e[0],s+=n*_e,o+=n*Se,a+=n*Re,c+=n*ze,u+=n*He,l+=n*$e,h+=n*Ge,f+=n*We,d+=n*hr,p+=n*fr,m+=n*dr,g+=n*pr,y+=n*mr,b+=n*gr,E+=n*yr,R+=n*wr,n=e[1],o+=n*_e,a+=n*Se,c+=n*Re,u+=n*ze,l+=n*He,h+=n*$e,f+=n*Ge,d+=n*We,p+=n*hr,m+=n*fr,g+=n*dr,y+=n*pr,b+=n*mr,E+=n*gr,R+=n*yr,v+=n*wr,n=e[2],a+=n*_e,c+=n*Se,u+=n*Re,l+=n*ze,h+=n*He,f+=n*$e,d+=n*Ge,p+=n*We,m+=n*hr,g+=n*fr,y+=n*dr,b+=n*pr,E+=n*mr,R+=n*gr,v+=n*yr,_+=n*wr,n=e[3],c+=n*_e,u+=n*Se,l+=n*Re,h+=n*ze,f+=n*He,d+=n*$e,p+=n*Ge,m+=n*We,g+=n*hr,y+=n*fr,b+=n*dr,E+=n*pr,R+=n*mr,v+=n*gr,_+=n*yr,I+=n*wr,n=e[4],u+=n*_e,l+=n*Se,h+=n*Re,f+=n*ze,d+=n*He,p+=n*$e,m+=n*Ge,g+=n*We,y+=n*hr,b+=n*fr,E+=n*dr,R+=n*pr,v+=n*mr,_+=n*gr,I+=n*yr,P+=n*wr,n=e[5],l+=n*_e,h+=n*Se,f+=n*Re,d+=n*ze,p+=n*He,m+=n*$e,g+=n*Ge,y+=n*We,b+=n*hr,E+=n*fr,R+=n*dr,v+=n*pr,_+=n*mr,I+=n*gr,P+=n*yr,M+=n*wr,n=e[6],h+=n*_e,f+=n*Se,d+=n*Re,p+=n*ze,m+=n*He,g+=n*$e,y+=n*Ge,b+=n*We,E+=n*hr,R+=n*fr,v+=n*dr,_+=n*pr,I+=n*mr,P+=n*gr,M+=n*yr,W+=n*wr,n=e[7],f+=n*_e,d+=n*Se,p+=n*Re,m+=n*ze,g+=n*He,y+=n*$e,b+=n*Ge,E+=n*We,R+=n*hr,v+=n*fr,_+=n*dr,I+=n*pr,P+=n*mr,M+=n*gr,W+=n*yr,ue+=n*wr,n=e[8],d+=n*_e,p+=n*Se,m+=n*Re,g+=n*ze,y+=n*He,b+=n*$e,E+=n*Ge,R+=n*We,v+=n*hr,_+=n*fr,I+=n*dr,P+=n*pr,M+=n*mr,W+=n*gr,ue+=n*yr,le+=n*wr,n=e[9],p+=n*_e,m+=n*Se,g+=n*Re,y+=n*ze,b+=n*He,E+=n*$e,R+=n*Ge,v+=n*We,_+=n*hr,I+=n*fr,P+=n*dr,M+=n*pr,W+=n*mr,ue+=n*gr,le+=n*yr,Ce+=n*wr,n=e[10],m+=n*_e,g+=n*Se,y+=n*Re,b+=n*ze,E+=n*He,R+=n*$e,v+=n*Ge,_+=n*We,I+=n*hr,P+=n*fr,M+=n*dr,W+=n*pr,ue+=n*mr,le+=n*gr,Ce+=n*yr,Ve+=n*wr,n=e[11],g+=n*_e,y+=n*Se,b+=n*Re,E+=n*ze,R+=n*He,v+=n*$e,_+=n*Ge,I+=n*We,P+=n*hr,M+=n*fr,W+=n*dr,ue+=n*pr,le+=n*mr,Ce+=n*gr,Ve+=n*yr,ae+=n*wr,n=e[12],y+=n*_e,b+=n*Se,E+=n*Re,R+=n*ze,v+=n*He,_+=n*$e,I+=n*Ge,P+=n*We,M+=n*hr,W+=n*fr,ue+=n*dr,le+=n*pr,Ce+=n*mr,Ve+=n*gr,ae+=n*yr,de+=n*wr,n=e[13],b+=n*_e,E+=n*Se,R+=n*Re,v+=n*ze,_+=n*He,I+=n*$e,P+=n*Ge,M+=n*We,W+=n*hr,ue+=n*fr,le+=n*dr,Ce+=n*pr,Ve+=n*mr,ae+=n*gr,de+=n*yr,k+=n*wr,n=e[14],E+=n*_e,R+=n*Se,v+=n*Re,_+=n*ze,I+=n*He,P+=n*$e,M+=n*Ge,W+=n*We,ue+=n*hr,le+=n*fr,Ce+=n*dr,Ve+=n*pr,ae+=n*mr,de+=n*gr,k+=n*yr,fe+=n*wr,n=e[15],R+=n*_e,v+=n*Se,_+=n*Re,I+=n*ze,P+=n*He,M+=n*$e,W+=n*Ge,ue+=n*We,le+=n*hr,Ce+=n*fr,Ve+=n*dr,ae+=n*pr,de+=n*mr,k+=n*gr,fe+=n*yr,ut+=n*wr,s+=38*v,o+=38*_,a+=38*I,c+=38*P,u+=38*M,l+=38*W,h+=38*ue,f+=38*le,d+=38*Ce,p+=38*Ve,m+=38*ae,g+=38*de,y+=38*k,b+=38*fe,E+=38*ut,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=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=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=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=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,n=E+i+65535,i=Math.floor(n/65536),E=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=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=h+i+65535,i=Math.floor(n/65536),h=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=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=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,n=E+i+65535,i=Math.floor(n/65536),E=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,s+=i-1+37*(i-1),r[0]=s,r[1]=o,r[2]=a,r[3]=c,r[4]=u,r[5]=l,r[6]=h,r[7]=f,r[8]=d,r[9]=p,r[10]=m,r[11]=g,r[12]=y,r[13]=b,r[14]=E,r[15]=R}function hl(r,e){ns(r,e,e)}function bF(r,e){let t=Ci();for(let n=0;n<16;n++)t[n]=e[n];for(let n=253;n>=0;n--)hl(t,t),n!==2&&n!==4&&ns(t,t,e);for(let n=0;n<16;n++)r[n]=t[n]}function Sm(r,e){let t=new Uint8Array(32),n=new Float64Array(80),i=Ci(),s=Ci(),o=Ci(),a=Ci(),c=Ci(),u=Ci();for(let d=0;d<31;d++)t[d]=r[d];t[31]=r[31]&127|64,t[0]&=248,wF(n,e);for(let d=0;d<16;d++)s[d]=n[d];i[0]=a[0]=1;for(let d=254;d>=0;--d){let p=t[d>>>3]>>>(d&7)&1;ll(i,s,p),ll(o,a,p),R0(c,i,o),I0(i,i,o),R0(o,s,a),I0(s,s,a),hl(a,c),hl(u,i),ns(i,o,i),ns(o,s,c),R0(c,i,o),I0(i,i,o),hl(s,i),I0(o,a,u),ns(i,o,gF),R0(i,i,a),ns(o,o,i),ns(i,a,u),ns(a,s,n),hl(s,c),ll(i,s,p),ll(o,a,p)}for(let d=0;d<16;d++)n[d+16]=i[d],n[d+32]=o[d],n[d+48]=s[d],n[d+64]=a[d];let l=n.subarray(32),h=n.subarray(16);bF(l,l),ns(h,h,l);let f=new Uint8Array(32);return yF(f,h),f}Nt.scalarMult=Sm;function kv(r){return Sm(r,Pv)}Nt.scalarMultBase=kv;function Nv(r){if(r.length!==Nt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${Nt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(r);return{publicKey:kv(e),secretKey:e}}Nt.generateKeyPairFromSeed=Nv;function EF(r){let e=(0,pF.randomBytes)(32,r),t=Nv(e);return(0,mF.wipe)(e),t}Nt.generateKeyPair=EF;function vF(r,e,t=!1){if(r.length!==Nt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==Nt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=Sm(r,e);if(t){let i=0;for(let s=0;s<n.length;s++)i|=n[s];if(i===0)throw new Error("X25519: invalid shared key")}return n}Nt.sharedKey=vF});var r4=T((Wce,vx)=>{vx.exports=r=>async function*(){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let i of r){typeof i=="string"&&(i=new TextEncoder().encode(i)),n+=t.decode(i,{stream:!0});let s=n.split(e);n=s.pop();for(let o=0;o<s.length;o++)yield JSON.parse(s[o])}n+=t.decode(),n&&(yield JSON.parse(n))}()});var _x=T((Yce,xx)=>{xx.exports=r=>async function*(){for await(let e of r)yield JSON.stringify(e)+`
|
|
16
|
+
`}()});var Sx=T((Qce,W0)=>{W0.exports=r4();W0.exports.parse=r4();W0.exports.stringify=_x()});var Tx=T(El=>{(function(){var r,e,t,n,i,s,o,a;a=function(c){var u,l,h,f;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[u,l,h,f].join(".")},o=function(c){var u,l,h,f,d,p;for(u=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>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"),s=t("a"),i=t("A"),e=function(c){var u,l,h,f,d;for(f=0,u=10,l="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,u=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,u=8,l="7")),d=h;h<c.length;){if("0"<=c[h]&&c[h]<=l)f=f*u+(t(c[h])-n)>>>0;else if(u===16)if("a"<=c[h]&&c[h]<="f")f=f*u+(10+t(c[h])-s)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*u+(10+t(c[h])-i)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===d)throw new Error("empty octet");return[f,h]},r=function(){function c(u,l){var h,f,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=o(l)}catch(m){throw h=m,new Error("Invalid mask: "+l)}for(f=d=32;d>=0;f=--d)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;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=(o(u)&this.maskLong)>>>0}catch(m){throw h=m,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):(o(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,h,f;for(f=o(this.first),h=o(this.last),l=0;f<=h;)u(a(f),f,l),l++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),El.ip2long=o,El.long2ip=a,El.Netmask=r}).call(El)});var kx=T((Px,X0)=>{(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"),s="%[0-9a-z]{1,}",o="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${o})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${o})|(?:::)(?:${o})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(d,p){if(d.indexOf("::")!==d.lastIndexOf("::"))return null;let m=0,g=-1,y=(d.match(a.zoneIndex)||[])[0],b,E;for(y&&(y=y.substring(1),d=d.replace(/%.+$/,""));(g=d.indexOf(":",g+1))>=0;)m++;if(d.substr(0,2)==="::"&&m--,d.substr(-2,2)==="::"&&m--,m>p)return null;for(E=p-m,b=":";E--;)b+="0:";return d=d.replace("::",b),d[0]===":"&&(d=d.slice(1)),d[d.length-1]===":"&&(d=d.slice(0,-1)),p=function(){let R=d.split(":"),v=[];for(let _=0;_<R.length;_++)v.push(parseInt(R[_],16));return v}(),{parts:p,zoneId:y}}function u(d,p,m,g){if(d.length!==p.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,b;for(;g>0;){if(b=m-g,b<0&&(b=0),d[y]>>b!==p[y]>>b)return!1;g-=m,y+=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 h(d,p){for(;d.length<p;)d=`0${d}`;return d}let f={};f.IPv4=function(){function d(p){if(p.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let m,g;for(m=0;m<p.length;m++)if(g=p[m],!(0<=g&&g<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=p}return d.prototype.SpecialRanges={unspecified:[[new d([0,0,0,0]),8]],broadcast:[[new d([255,255,255,255]),32]],multicast:[[new d([224,0,0,0]),4]],linkLocal:[[new d([169,254,0,0]),16]],loopback:[[new d([127,0,0,0]),8]],carrierGradeNat:[[new d([100,64,0,0]),10]],private:[[new d([10,0,0,0]),8],[new d([172,16,0,0]),12],[new d([192,168,0,0]),16]],reserved:[[new d([192,0,0,0]),24],[new d([192,0,2,0]),24],[new d([192,88,99,0]),24],[new d([198,51,100,0]),24],[new d([203,0,113,0]),24],[new d([240,0,0,0]),4]]},d.prototype.kind=function(){return"ipv4"},d.prototype.match=function(p,m){let g;if(m===void 0&&(g=p,p=g[0],m=g[1]),p.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,p.octets,8,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,g={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},y,b,E;for(y=3;y>=0;y-=1)if(b=this.octets[y],b in g){if(E=g[b],m&&E!==0)return null;E!==8&&(m=!0),p+=E}else return null;return 32-p},d.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){return this.octets.slice(0)},d.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse(`::ffff:${this.toString()}`)},d.prototype.toNormalizedString=function(){return this.toString()},d.prototype.toString=function(){return this.octets.join(".")},d}(),f.IPv4.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),g=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],b=0;for(;b<4;)y.push(parseInt(m[b],10)|parseInt(g[b],10)^255),b++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(d){return this.parser(d)!==null},f.IPv4.isValid=function(d){try{return new this(this.parser(d)),!0}catch{return!1}},f.IPv4.isValidFourPartDecimal=function(d){return!!(f.IPv4.isValid(d)&&d.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(d){let p,m,g,y,b;try{for(p=this.parseCIDR(d),g=p[0].toByteArray(),b=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],m=0;m<4;)y.push(parseInt(g[m],10)&parseInt(b[m],10)),m++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.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)},f.IPv4.parseCIDR=function(d){let p;if(p=d.match(/^(.+)\/(\d+)$/)){let m=parseInt(p[2]);if(m>=0&&m<=32){let g=[this.parse(p[1]),m];return Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(d){let p,m,g;if(p=d.match(t.fourOctet))return function(){let y=p.slice(1,6),b=[];for(let E=0;E<y.length;E++)m=y[E],b.push(l(m));return b}();if(p=d.match(t.longValue)){if(g=l(p[1]),g>4294967295||g<0)throw new Error("ipaddr: address outside defined range");return function(){let y=[],b;for(b=0;b<=24;b+=8)y.push(g>>b&255);return y}().reverse()}else return(p=d.match(t.twoOctet))?function(){let y=p.slice(1,4),b=[];if(g=l(y[1]),g>16777215||g<0)throw new Error("ipaddr: address outside defined range");return b.push(l(y[0])),b.push(g>>16&255),b.push(g>>8&255),b.push(g&255),b}():(p=d.match(t.threeOctet))?function(){let y=p.slice(1,5),b=[];if(g=l(y[2]),g>65535||g<0)throw new Error("ipaddr: address outside defined range");return b.push(l(y[0])),b.push(l(y[1])),b.push(g>>8&255),b.push(g&255),b}():null},f.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],m=0,g=Math.floor(d/8);for(;m<g;)p[m]=255,m++;return g<4&&(p[g]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},f.IPv6=function(){function d(p,m){let g,y;if(p.length===16)for(this.parts=[],g=0;g<=14;g+=2)this.parts.push(p[g]<<8|p[g+1]);else if(p.length===8)this.parts=p;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(g=0;g<this.parts.length;g++)if(y=this.parts[g],!(0<=y&&y<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");m&&(this.zoneId=m)}return d.prototype.SpecialRanges={unspecified:[new d([0,0,0,0,0,0,0,0]),128],linkLocal:[new d([65152,0,0,0,0,0,0,0]),10],multicast:[new d([65280,0,0,0,0,0,0,0]),8],loopback:[new d([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new d([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new d([0,0,0,0,0,65535,0,0]),96],rfc6145:[new d([0,0,0,0,65535,0,0,0]),96],rfc6052:[new d([100,65435,0,0,0,0,0,0]),96],"6to4":[new d([8194,0,0,0,0,0,0,0]),16],teredo:[new d([8193,0,0,0,0,0,0,0]),32],reserved:[[new d([8193,3512,0,0,0,0,0,0]),32]]},d.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},d.prototype.kind=function(){return"ipv6"},d.prototype.match=function(p,m){let g;if(m===void 0&&(g=p,p=g[0],m=g[1]),p.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,p.parts,16,m)},d.prototype.prefixLengthFromSubnetMask=function(){let p=0,m=!1,g={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},y,b;for(let E=7;E>=0;E-=1)if(y=this.parts[E],y in g){if(b=g[y],m&&b!==0)return null;b!==16&&(m=!0),p+=b}else return null;return 128-p},d.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},d.prototype.toByteArray=function(){let p,m=[],g=this.parts;for(let y=0;y<g.length;y++)p=g[y],m.push(p>>8),m.push(p&255);return m},d.prototype.toFixedLengthString=function(){let p=function(){let g=[];for(let y=0;y<this.parts.length;y++)g.push(h(this.parts[y].toString(16),4));return g}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let p=this.parts.slice(-2),m=p[0],g=p[1];return new f.IPv4([m>>8,m&255,g>>8,g&255])},d.prototype.toNormalizedString=function(){let p=function(){let g=[];for(let y=0;y<this.parts.length;y++)g.push(this.parts[y].toString(16));return g}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),p+m},d.prototype.toRFC5952String=function(){let p=/((^|:)(0(:|$)){2,})/g,m=this.toNormalizedString(),g=0,y=-1,b;for(;b=p.exec(m);)b[0].length>y&&(g=b.index,y=b[0].length);return y<0?m:`${m.substring(0,g)}::${m.substring(g+y)}`},d.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},d}(),f.IPv6.broadcastAddressFromCIDR=function(d){try{let p=this.parseCIDR(d),m=p[0].toByteArray(),g=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],b=0;for(;b<16;)y.push(parseInt(m[b],10)|parseInt(g[b],10)^255),b++;return new this(y)}catch(p){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${p})`)}},f.IPv6.isIPv6=function(d){return this.parser(d)!==null},f.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}},f.IPv6.networkAddressFromCIDR=function(d){let p,m,g,y,b;try{for(p=this.parseCIDR(d),g=p[0].toByteArray(),b=this.subnetMaskFromPrefixLength(p[1]).toByteArray(),y=[],m=0;m<16;)y.push(parseInt(g[m],10)&parseInt(b[m],10)),m++;return new this(y)}catch(E){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${E})`)}},f.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)},f.IPv6.parseCIDR=function(d){let p,m,g;if((m=d.match(/^(.+)\/(\d+)$/))&&(p=parseInt(m[2]),p>=0&&p<=128))return g=[this.parse(m[1]),p],Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(d){let p,m,g,y,b,E;if(g=d.match(a.deprecatedTransitional))return this.parser(`::ffff:${g[1]}`);if(a.native.test(d))return c(d,8);if((g=d.match(a.transitional))&&(E=g[6]||"",p=c(g[1].slice(0,-1)+E,6),p.parts)){for(b=[parseInt(g[2]),parseInt(g[3]),parseInt(g[4]),parseInt(g[5])],m=0;m<b.length;m++)if(y=b[m],!(0<=y&&y<=255))return null;return p.parts.push(b[0]<<8|b[1]),p.parts.push(b[2]<<8|b[3]),{parts:p.parts,zoneId:p.zoneId}}return null},f.IPv6.subnetMaskFromPrefixLength=function(d){if(d=parseInt(d),d<0||d>128)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],m=0,g=Math.floor(d/8);for(;m<g;)p[m]=255,m++;return g<16&&(p[g]=Math.pow(2,d%8)-1<<8-d%8),new this(p)},f.fromByteArray=function(d){let p=d.length;if(p===4)return new f.IPv4(d);if(p===16)return new f.IPv6(d);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},f.isValid=function(d){return f.IPv6.isValid(d)||f.IPv4.isValid(d)},f.parse=function(d){if(f.IPv6.isValid(d))return f.IPv6.parse(d);if(f.IPv4.isValid(d))return f.IPv4.parse(d);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},f.parseCIDR=function(d){try{return f.IPv6.parseCIDR(d)}catch{try{return f.IPv4.parseCIDR(d)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},f.process=function(d){let p=this.parse(d);return p.kind()==="ipv6"&&p.isIPv4MappedAddress()?p.toIPv4Address():p},f.subnetMatch=function(d,p,m){let g,y,b,E;m==null&&(m="unicast");for(y in p)if(Object.prototype.hasOwnProperty.call(p,y)){for(b=p[y],b[0]&&!(b[0]instanceof Array)&&(b=[b]),g=0;g<b.length;g++)if(E=b[g],d.kind()===E[0].kind()&&d.match.apply(d,E))return y}return m},typeof X0<"u"&&X0.exports?X0.exports=f:r.ipaddr=f})(Px)});var t_=T((qle,e_)=>{e_.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(s,o){t[s]=o,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var o=t[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){t[s]!==void 0?t[s]=o:i(s,o)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Tl=T((S0e,p_)=>{p_.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 g_=T((R0e,m_)=>{m_.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 w_=T((I0e,y_)=>{var FK=g_();y_.exports=FK});var fn=T((D0e,b_)=>{b_.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 vc=T((P0e,v_)=>{var g4=Tl(),KK=w_(),E_=fn();v_.exports=class extends g4{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed||e.inmemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration||e.inmemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new KK}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,s,o={}){let a=this._getRateLimiterRes(n,i,s);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,o)),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<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,t,n,i,s,o=!1,a={}){this.insuranceLimiter instanceof g4?this.insuranceLimiter[t](s,o,a).then(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 g4))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 s=(n>=0?n:this.duration)*1e3;return this._block(this.getKey(e),t,s,i)}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return s(new E_(0,a));this._upsert(o,t,this._getKeySecDuration(n)*1e3,!1,n).then(c=>{this._afterConsume(i,s,o,t,c)}).catch(c=>{this._handleError(c,"consume",i,s,e,t,n)})})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,t,a))}).catch(a=>{this._handleError(a,"penalty",s,o,e,t,n)})})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise((s,o)=>{this._upsert(i,-t,this._getKeySecDuration(n)*1e3,!1,n).then(a=>{s(this._getRateLimiterRes(i,-t,a))}).catch(a=>{this._handleError(a,"reward",s,o,e,t,n)})})}get(e,t={}){let n=this.getKey(e);return new Promise((i,s)=>{this._get(n,t).then(o=>{i(o===null||typeof o>"u"?null:this._getRateLimiterRes(n,0,o))}).catch(o=>{this._handleError(o,"get",i,s,e,t)})})}delete(e,t={}){let n=this.getKey(e);return new Promise((i,s)=>{this._delete(n,t).then(o=>{this._inMemoryBlockedKeys.delete(n),i(o)}).catch(o=>{this._handleError(o,"delete",i,s,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((s,o)=>{this._upsert(e,t,n,!0,i).then(()=>{s(new E_(0,n>0?n:-1,t))}).catch(a=>{this._handleError(a,"block",s,o,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,s={}){throw new Error("You have to implement the method '_upsert'!")}}});var S_=T((k0e,__)=>{var qK=vc(),VK=fn(),x_="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} ",y4=class extends qK{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:x_})}_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,s]=n;Array.isArray(i)&&([,i]=i,[,s]=s);let o=new VK;return o.consumedPoints=parseInt(i),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=s,o}_upsert(e,t,n,i=!1){return new Promise((s,o)=>{if(!this._isRedisReady())return o(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?o(u):s(l));else if(a>0){let u=function(l,h){return l?o(l):s(h)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,a,u):this.client.eval(x_,1,e,t,a,u)}else c.incrby(e,t).pttl(e).exec((u,l)=>u?o(u):s(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,s)=>{if(i)n(i);else{let[o]=s;if(o===null)return t(null);t(s)}})})}_delete(e){return new Promise((t,n)=>{this.client.del(e,(i,s)=>{i?n(i):t(s>0)})})}};__.exports=y4});var I_=T((N0e,R_)=>{var zK=vc(),HK=fn();function A_(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 Dl=class extends zK{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=A_(this.client)}):(this._initCollection(),this._driverVersion=A_(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?Dl.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 HK,s;return typeof n.value>"u"?s=n:s=n.value,i.isFirstInDuration=s.points===t,i.consumedPoints=s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire!==null?Math.max(new Date(s.expire).getTime()-Date.now(),0):-1,i}_upsert(e,t,n,i=!1,s={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=s.attrs||{},a,c;i?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:n>0?new Date(Date.now()+n):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:n>0?new Date(Date.now()+n):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));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,h)=>{this._collection.findOneAndUpdate(a,c,u).then(f=>{l(f)}).catch(f=>{if(f&&f.code===11e3){let d=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),p={$set:Object.assign({key:e,points:t,expire:n>0?new Date(Date.now()+n):null},o)};this._collection.findOneAndUpdate(d,p,u).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,t,n,i).then(g=>l(g)).catch(g=>h(g)):h(m)})}else h(f)})})}_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(s=>s.deletedCount>0)}};R_.exports=Dl});var D_=T((L0e,T_)=>{var $K=vc(),GK=fn(),w4=class extends $K{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(),s=>{if(s)return this._releaseConnection(n),t(s);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 GK,[s]=n;return i.isFirstInDuration=t===s.points,i.consumedPoints=i.isFirstInDuration?t:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_upsertTransaction(e,t,n,i,s){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let u=Date.now(),l=i>0?u+i:null,h,f;s?(h=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
|
17
|
+
ON DUPLICATE KEY UPDATE
|
|
18
|
+
points = ?,
|
|
19
|
+
expire = ?;`,f=[this.dbName,this.tableName,t,n,l,n,l]):(h=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
|
20
|
+
ON DUPLICATE KEY UPDATE
|
|
21
|
+
points = IF(expire <= ?, ?, points + (?)),
|
|
22
|
+
expire = IF(expire <= ?, ?, expire);`,f=[this.dbName,this.tableName,t,n,l,u,n,n,u,l]),e.query(h,f,d=>{if(d)return e.rollback(),a(d);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(p,m)=>{if(p)return e.rollback(),a(p);e.query("COMMIT",g=>{if(g)return e.rollback(),a(g);o(m)})})})})})}_upsert(e,t,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(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()],(s,o)=>{s?n(s):o.length===0?t(null):t(o),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],(s,o)=>{s?n(s):t(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};T_.exports=w4});var P_=T((O0e,C_)=>{var WK=vc(),YK=fn(),b4=class extends WK{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} (
|
|
23
|
+
key varchar(255) PRIMARY KEY,
|
|
24
|
+
points integer NOT NULL DEFAULT 0,
|
|
25
|
+
expire bigint
|
|
26
|
+
);`}get clientType(){return this._clientType}set clientType(e){let t=this.client.constructor.name;if(typeof e>"u")if(t==="Client")e="client";else if(t==="Pool"||t==="BoundPool")e="pool";else if(t==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}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 YK,s=n.rows[0];return i.isFirstInDuration=t===s.points,i.consumedPoints=i.isFirstInDuration?t:s.points,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=s.expire?Math.max(s.expire-Date.now(),0):-1,i}_query(e){let n={name:`${this.tableName.toLowerCase()}:${e.name}`,text:e.text,values:e.values};return new Promise((i,s)=>{this._getConnection().then(o=>{o.query(n).then(a=>{i(a),this._releaseConnection(o)}).catch(a=>{s(a),this._releaseConnection(o)})}).catch(o=>{s(o)})})}_upsert(e,t,n,i=!1){if(!this.tableCreated)return Promise.reject(Error("Table is not created yet"));let s=n>0?Date.now()+n:null,o=i?" $3 ":` CASE
|
|
27
|
+
WHEN ${this.tableName}.expire <= $4 THEN $3
|
|
28
|
+
ELSE ${this.tableName}.expire
|
|
29
|
+
END `;return this._query({name:i?"rlflx-upsert-force":"rlflx-upsert",text:`
|
|
30
|
+
INSERT INTO ${this.tableName} VALUES ($1, $2, $3)
|
|
31
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
32
|
+
points = CASE
|
|
33
|
+
WHEN (${this.tableName}.expire <= $4 OR 1=${i?1:0}) THEN $2
|
|
34
|
+
ELSE ${this.tableName}.points + ($2)
|
|
35
|
+
END,
|
|
36
|
+
expire = ${o}
|
|
37
|
+
RETURNING points, expire;`,values:[e,t,s,Date.now()]})}_get(e){return this.tableCreated?new Promise((t,n)=>{this._query({name:"rlflx-get",text:`
|
|
38
|
+
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"))}};C_.exports=b4});var k_=T(()=>{});var L_=T((F0e,N_)=>{N_.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 B_=T((q0e,O_)=>{var QK=L_(),E4=fn();O_.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 E4(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 QK(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 E4(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 E4(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 x4=T((V0e,U_)=>{var XK=Tl(),jK=B_(),M_=fn(),v4=class extends XK{constructor(e={}){super(e),this._memoryStorage=new jK}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(o,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(o,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(i,u,c)}else i(c)})}penalty(e,t=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,t=1,n={}){let i=this.getKey(e);return new Promise(s=>{let o=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,t){let n=t*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,t),Promise.resolve(new M_(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 M_(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)))}};U_.exports=v4});var $_=T((z0e,H_)=>{var F_=k_(),ZK=Ns(),JK=Tl(),q_=x4(),eq=fn(),Ln="rate_limiter_flexible",Sc=null,K_=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:Ln,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:i})},V_=function(r){setTimeout(()=>{this._initiated?process.send(r):typeof this._promises[r.promiseId]<"u"&&V_.call(this,r)},30)},xc=function(r,e,t,n,i){let s={channel:Ln,keyPrefix:this.keyPrefix,func:r,promiseId:e,data:{key:t,arg:n,opts:i}};this._initiated?process.send(s):V_.call(this,s)},z_=function(r,e){if(!e||e.channel!==Ln||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=>{K_(r,e,"resolve",n)}).catch(n=>{K_(r,e,"reject",n)})},tq=function(r){if(!r||r.channel!==Ln||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 eq(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]}},rq=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},_c=function(r,e){let t=process.hrtime(),n=t[0].toString()+t[1].toString();return typeof this._promises[n]<"u"&&(n+=ZK.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},_4=class{constructor(){if(Sc)return Sc;this._rateLimiters={},F_.setMaxListeners(0),F_.on("message",(e,t)=>{t&&t.channel===Ln&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new q_(t.opts)),e.send({channel:Ln,type:"init",keyPrefix:t.opts.keyPrefix})):z_.call(this,e,t)}),Sc=this}},S4=class{constructor(e){if(Sc)return Sc;this._rateLimiters={},e.launchBus((t,n)=>{n.on("process:msg",i=>{let s=i.raw;if(s&&s.channel===Ln&&s.type==="init")typeof this._rateLimiters[s.opts.keyPrefix]>"u"&&(this._rateLimiters[s.opts.keyPrefix]=new q_(s.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:Ln,channel:Ln,type:"init",keyPrefix:s.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=Ln,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};z_.call(this,o,s)}})}),Sc=this}},A4=class extends JK{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===Ln&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:tq.call(this,t)}),process.send({channel:Ln,type:"init",opts:rq.call(this)}),this._promises={}}consume(e,t=1,n={}){return new Promise((i,s)=>{let o=_c.call(this,i,s);xc.call(this,"consume",o,e,t,n)})}penalty(e,t=1,n={}){return new Promise((i,s)=>{let o=_c.call(this,i,s);xc.call(this,"penalty",o,e,t,n)})}reward(e,t=1,n={}){return new Promise((i,s)=>{let o=_c.call(this,i,s);xc.call(this,"reward",o,e,t,n)})}block(e,t,n={}){return new Promise((i,s)=>{let o=_c.call(this,i,s);xc.call(this,"block",o,e,t,n)})}get(e,t={}){return new Promise((n,i)=>{let s=_c.call(this,n,i);xc.call(this,"get",s,e,t)})}delete(e,t={}){return new Promise((n,i)=>{let s=_c.call(this,n,i);xc.call(this,"delete",s,e,t)})}};H_.exports={RateLimiterClusterMaster:_4,RateLimiterClusterMasterPM2:S4,RateLimiterCluster:A4}});var W_=T((H0e,G_)=>{var nq=vc(),iq=fn(),R4=class extends nq{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,n){let i=new iq;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,s={}){return new Promise((o,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 h={consumedPoints:t,msBeforeNext:u>0?u*1e3:-1};o(h)})}):this.client.incr(e,t,(l,h)=>{l||h===!1?this.client.add(e,t,u,(f,d)=>{if(f||!d)if(typeof s.attemptNumber>"u"||s.attemptNumber<3){let p=Object.assign({},s);p.attemptNumber=p.attemptNumber?p.attemptNumber+1:1,this._upsert(e,t,n,i,p).then(m=>o(m)).catch(m=>a(m))}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};o(p)})}):this.client.get(`${e}_expire`,(f,d)=>{if(f)a(f);else{let p=d===!1?0:d,m={consumedPoints:h,msBeforeNext:p>=0?Math.max(p-c,0):-1};o(m)}})})})}_get(e){return new Promise((t,n)=>{let i=Date.now();this.client.get(e,(s,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:o,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,s)=>{i?n(i):s===!1?t(s):this.client.del(`${e}_expire`,o=>{o?n(o):t(s)})})})}};G_.exports=R4});var X_=T((G0e,Q_)=>{var Y_=fn();Q_.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 Y_(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new Y_(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 Z_=T((Y0e,j_)=>{var sq=Tl();j_.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 sq))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 s=[];this._limiters.forEach(o=>{s.push(o.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(s).then(o=>{let a={},c=!1;o.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u<o.length;u++)c&&o[u].rejected===!0?a[this._limiters[u].keyPrefix]=o[u].rej:c||(a[this._limiters[u].keyPrefix]=o[u]);c?i(a):n(a)})})}}});var eS=T((X0e,J_)=>{J_.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 iS=T((Z0e,nS)=>{var tS=eS(),rS=4294967295,I4="limiter";nS.exports=class{constructor(e,t={maxQueueSize:rS}){this._queueLimiters={KEY_DEFAULT:new v1(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=I4){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=I4){return this._queueLimiters[t]||(this._queueLimiters[t]=new v1(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var v1=class{constructor(e,t={maxQueueSize:rS,key:I4}){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 tS(`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(s=>{n(s.remainingPoints)}).catch(s=>{s instanceof Error?i(s):(t._queueRequest.call(t,n,i,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),s.msBeforeNext)))})})}_queueRequest(e,t,n){let i=this;i._queue.length<i._maxQueueSize?i._queue.push({resolve:e,reject:t,tokens:n}):t(new tS(`Number of requests reached it's maximum ${i._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let t=e._queue.shift();e._limiterFlexible.consume(e._key,t.tokens).then(n=>{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 oS=T((e1e,sS)=>{var T4=fn();sS.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return new T4(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 T4?this._burstLimiter.consume(e,t,n).then(s=>Promise.resolve(this._combineRes(i,s))).catch(s=>s instanceof T4?Promise.reject(this._combineRes(i,s)):Promise.reject(s)):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 D4=T((t1e,aS)=>{var oq=S_(),aq=I_(),cq=D_(),uq=P_(),{RateLimiterClusterMaster:lq,RateLimiterClusterMasterPM2:hq,RateLimiterCluster:fq}=$_(),dq=x4(),pq=W_(),mq=X_(),gq=Z_(),yq=iS(),wq=oS(),bq=fn();aS.exports={RateLimiterRedis:oq,RateLimiterMongo:aq,RateLimiterMySQL:cq,RateLimiterPostgres:uq,RateLimiterMemory:dq,RateLimiterMemcache:pq,RateLimiterClusterMaster:lq,RateLimiterClusterMasterPM2:hq,RateLimiterCluster:fq,RLWrapperBlackAndWhite:mq,RateLimiterUnion:gq,RateLimiterQueue:yq,BurstyRateLimiter:wq,RateLimiterRes:bq}});var US=T((Kde,MS)=>{"use strict";function Zq(r){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t<e.length;t++)e[t]=255;for(var n=0;n<r.length;n++){var i=r.charAt(n),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=n}var o=r.length,a=r.charAt(0),c=Math.log(o)/Math.log(256),u=Math.log(256)/Math.log(o);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var p=0,m=0,g=0,y=d.length;g!==y&&d[g]===0;)g++,p++;for(var b=(y-g)*u+1>>>0,E=new Uint8Array(b);g!==y;){for(var R=d[g],v=0,_=b-1;(R!==0||v<m)&&_!==-1;_--,v++)R+=256*E[_]>>>0,E[_]=R%o>>>0,R=R/o>>>0;if(R!==0)throw new Error("Non-zero carry");m=v,g++}for(var I=b-m;I!==b&&E[I]===0;)I++;for(var P=a.repeat(p);I<b;++I)P+=r.charAt(E[I]);return P}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var p=0;if(d[p]!==" "){for(var m=0,g=0;d[p]===a;)m++,p++;for(var y=(d.length-p)*c+1>>>0,b=new Uint8Array(y);d[p];){var E=e[d.charCodeAt(p)];if(E===255)return;for(var R=0,v=y-1;(E!==0||R<g)&&v!==-1;v--,R++)E+=o*b[v]>>>0,b[v]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=R,p++}if(d[p]!==" "){for(var _=y-g;_!==y&&b[_]===0;)_++;for(var I=new Uint8Array(m+(y-_)),P=m;_!==y;)I[P++]=b[_++];return I}}}function f(d){var p=h(d);if(p)return p;throw new Error("Non-base"+o+" character")}return{encode:l,decodeUnsafe:h,decode:f}}MS.exports=Zq});var k1=T((qde,FS)=>{"use strict";var Jq=new TextDecoder,eV=r=>Jq.decode(r),tV=new TextEncoder,rV=r=>tV.encode(r);function nV(r,e){let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}FS.exports={decodeText:eV,encodeText:rV,concat:nV}});var qS=T((Vde,KS)=>{"use strict";var{encodeText:iV}=k1(),J4=class{constructor(e,t,n,i){this.name=e,this.code=t,this.codeBuf=iV(this.code),this.alphabet=i,this.codec=n(i)}encode(e){return this.codec.encode(e)}decode(e){for(let t of e)if(this.alphabet&&this.alphabet.indexOf(t)<0)throw new Error(`invalid character '${t}' in '${e}'`);return this.codec.decode(e)}};KS.exports=J4});var zS=T((zde,VS)=>{"use strict";var sV=(r,e,t)=>{let n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),o=0,a=0,c=0;for(let u=0;u<i;++u){let l=n[r[u]];if(l===void 0)throw new SyntaxError("Invalid character "+r[u]);a=a<<t|l,o+=t,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=t||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s},oV=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},aV=r=>e=>({encode(t){return oV(t,e,r)},decode(t){return sV(t,e,r)}});VS.exports={rfc4648:aV}});var WS=T((Hde,GS)=>{"use strict";var Nl=US(),cV=qS(),{rfc4648:ur}=zS(),{decodeText:uV,encodeText:lV}=k1(),hV=()=>({encode:uV,decode:lV}),HS=[["identity","\0",hV,""],["base2","0",ur(1),"01"],["base8","7",ur(3),"01234567"],["base10","9",Nl,"0123456789"],["base16","f",ur(4),"0123456789abcdef"],["base16upper","F",ur(4),"0123456789ABCDEF"],["base32hex","v",ur(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",ur(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",ur(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",ur(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",ur(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",ur(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",ur(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",ur(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",ur(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",Nl,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",Nl,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",Nl,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",Nl,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",ur(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",ur(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",ur(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",ur(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],$S=HS.reduce((r,e)=>(r[e[0]]=new cV(e[0],e[1],e[2],e[3]),r),{}),fV=HS.reduce((r,e)=>(r[e[1]]=$S[e[0]],r),{});GS.exports={names:$S,codes:fV}});var XS=T((us,QS)=>{"use strict";var Dc=WS(),{encodeText:dV,decodeText:N1,concat:YS}=k1();function pV(r,e){if(!e)throw new Error("requires an encoded Uint8Array");let{name:t,codeBuf:n}=Zo(r);return wV(t,e),YS([n,e],n.length+e.length)}function mV(r,e){let t=Zo(r),n=dV(t.encode(e));return YS([t.codeBuf,n],t.codeBuf.length+n.length)}function gV(r){r instanceof Uint8Array&&(r=N1(r));let e=r[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(e)&&(r=r.toLowerCase()),Zo(r[0]).decode(r.substring(1))}function yV(r){if(r instanceof Uint8Array&&(r=N1(r)),Object.prototype.toString.call(r)!=="[object String]")return!1;try{return Zo(r[0]).name}catch{return!1}}function wV(r,e){Zo(r).decode(N1(e))}function Zo(r){if(Object.prototype.hasOwnProperty.call(Dc.names,r))return Dc.names[r];if(Object.prototype.hasOwnProperty.call(Dc.codes,r))return Dc.codes[r];throw new Error(`Unsupported encoding: ${r}`)}function bV(r){return r instanceof Uint8Array&&(r=N1(r)),Zo(r[0])}us=QS.exports=pV;us.encode=mV;us.decode=gV;us.isEncoded=yV;us.encoding=Zo;us.encodingFromData=bV;var EV=Object.freeze(Dc.names),vV=Object.freeze(Dc.codes);us.names=EV;us.codes=vV});var eA=T(($de,JS)=>{JS.exports=ZS;var jS=128,xV=127,_V=~xV,SV=Math.pow(2,31);function ZS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=SV;)e[t++]=r&255|jS,r/=128;for(;r&_V;)e[t++]=r&255|jS,r>>>=7;return e[t]=r|0,ZS.bytes=t-n+1,e}});var nA=T((Gde,rA)=>{rA.exports=e8;var AV=128,tA=127;function e8(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw e8.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&tA)<<i:(o&tA)*Math.pow(2,i),i+=7}while(o>=AV);return e8.bytes=s-n,t}});var sA=T((Wde,iA)=>{var RV=Math.pow(2,7),IV=Math.pow(2,14),TV=Math.pow(2,21),DV=Math.pow(2,28),CV=Math.pow(2,35),PV=Math.pow(2,42),kV=Math.pow(2,49),NV=Math.pow(2,56),LV=Math.pow(2,63);iA.exports=function(r){return r<RV?1:r<IV?2:r<TV?3:r<DV?4:r<CV?5:r<PV?6:r<kV?7:r<NV?8:r<LV?9:10}});var aA=T((Yde,oA)=>{oA.exports={encode:eA(),decode:nA(),encodingLength:sA()}});var uA=T((Qde,cA)=>{"use strict";var OV=Object.freeze({identity:0,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,"murmur3-128":34,"murmur3-32":35,"dbl-sha2-256":86,md4:212,md5:213,bmt:214,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082});cA.exports={names:OV}});function BV(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var E=(b-y)*l+1>>>0,R=new Uint8Array(E);y!==b;){for(var v=p[y],_=0,I=E-1;(v!==0||_<g)&&I!==-1;I--,_++)v+=256*R[I]>>>0,R[I]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=_,y++}for(var P=E-g;P!==E&&R[P]===0;)P++;for(var M=c.repeat(m);P<E;++P)M+=r.charAt(R[P]);return M}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,E=new Uint8Array(b);p[m];){var R=t[p.charCodeAt(m)];if(R===255)return;for(var v=0,_=b-1;(R!==0||v<y)&&_!==-1;_--,v++)R+=a*E[_]>>>0,E[_]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");y=v,m++}if(p[m]!==" "){for(var I=b-y;I!==b&&E[I]===0;)I++;for(var P=new Uint8Array(g+(b-I)),M=g;I!==b;)P[M++]=E[I++];return P}}}function d(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var MV,UV,lA,hA=je(()=>{MV=BV,UV=MV,lA=UV});var jde,fA,ls,dA,pA,so=je(()=>{jde=new Uint8Array(0),fA=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},ls=r=>{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")},dA=r=>new TextEncoder().encode(r),pA=r=>new TextDecoder().decode(r)});var t8,r8,n8,gA,i8,Cc,oo,FV,KV,Lt,ai=je(()=>{hA();so();t8=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")}},r8=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 gA(this,e)}},n8=class{constructor(e){this.decoders=e}or(e){return gA(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`)}},gA=(r,e)=>new n8({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),i8=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new t8(e,t,n),this.decoder=new r8(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Cc=({name:r,prefix:e,encode:t,decode:n})=>new i8(r,e,t,n),oo=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=lA(t,e);return Cc({prefix:r,name:e,encode:n,decode:s=>ls(i(s))})},FV=(r,e,t,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},KV=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},Lt=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Cc({prefix:e,name:r,encode(i){return KV(i,n,t)},decode(i){return FV(i,n,t,r)}})});var s8={};Ae(s8,{identity:()=>qV});var qV,yA=je(()=>{ai();so();qV=Cc({prefix:"\0",name:"identity",encode:r=>pA(r),decode:r=>dA(r)})});var o8={};Ae(o8,{base2:()=>VV});var VV,wA=je(()=>{ai();VV=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var a8={};Ae(a8,{base8:()=>zV});var zV,bA=je(()=>{ai();zV=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var c8={};Ae(c8,{base10:()=>HV});var HV,EA=je(()=>{ai();HV=oo({prefix:"9",name:"base10",alphabet:"0123456789"})});var u8={};Ae(u8,{base16:()=>$V,base16upper:()=>GV});var $V,GV,vA=je(()=>{ai();$V=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),GV=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var l8={};Ae(l8,{base32:()=>Pc,base32hex:()=>XV,base32hexpad:()=>ZV,base32hexpadupper:()=>JV,base32hexupper:()=>jV,base32pad:()=>YV,base32padupper:()=>QV,base32upper:()=>WV,base32z:()=>ez});var Pc,WV,YV,QV,XV,jV,ZV,JV,ez,h8=je(()=>{ai();Pc=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),WV=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),YV=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),QV=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),XV=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jV=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZV=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),JV=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ez=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var f8={};Ae(f8,{base36:()=>tz,base36upper:()=>rz});var tz,rz,xA=je(()=>{ai();tz=oo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rz=oo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var d8={};Ae(d8,{base58btc:()=>ki,base58flickr:()=>nz});var ki,nz,p8=je(()=>{ai();ki=oo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nz=oo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var m8={};Ae(m8,{base64:()=>iz,base64pad:()=>sz,base64url:()=>oz,base64urlpad:()=>az});var iz,sz,oz,az,_A=je(()=>{ai();iz=Lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sz=Lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oz=Lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),az=Lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var g8={};Ae(g8,{base256emoji:()=>fz});function lz(r){return r.reduce((e,t)=>(e+=cz[t],e),"")}function hz(r){let e=[];for(let t of r){let n=uz[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var SA,cz,uz,fz,AA=je(()=>{ai();SA=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}"),cz=SA.reduce((r,e,t)=>(r[t]=e,r),[]),uz=SA.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);fz=Cc({prefix:"\u{1F680}",name:"base256emoji",encode:lz,decode:hz})});function TA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gz;)e[t++]=r&255|RA,r/=128;for(;r&mz;)e[t++]=r&255|RA,r>>>=7;return e[t]=r|0,TA.bytes=t-n+1,e}function y8(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw y8.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&IA)<<i:(o&IA)*Math.pow(2,i),i+=7}while(o>=wz);return y8.bytes=s-n,t}var dz,RA,pz,mz,gz,yz,wz,IA,bz,Ez,vz,xz,_z,Sz,Az,Rz,Iz,Tz,Dz,Cz,Ll,DA=je(()=>{dz=TA,RA=128,pz=127,mz=~pz,gz=Math.pow(2,31);yz=y8,wz=128,IA=127;bz=Math.pow(2,7),Ez=Math.pow(2,14),vz=Math.pow(2,21),xz=Math.pow(2,28),_z=Math.pow(2,35),Sz=Math.pow(2,42),Az=Math.pow(2,49),Rz=Math.pow(2,56),Iz=Math.pow(2,63),Tz=function(r){return r<bz?1:r<Ez?2:r<vz?3:r<xz?4:r<_z?5:r<Sz?6:r<Az?7:r<Rz?8:r<Iz?9:10},Dz={encode:dz,decode:yz,encodingLength:Tz},Cz=Dz,Ll=Cz});var Ol,kc,Nc,O1=je(()=>{DA();Ol=(r,e=0)=>[Ll.decode(r,e),Ll.decode.bytes],kc=(r,e,t=0)=>(Ll.encode(r,e,t),e),Nc=r=>Ll.encodingLength(r)});var Jo,CA,PA,Lc,Ml=je(()=>{so();O1();Jo=(r,e)=>{let t=e.byteLength,n=Nc(r),i=n+Nc(t),s=new Uint8Array(i+t);return kc(r,s,0),kc(t,s,n),s.set(e,i),new Lc(r,t,e,s)},CA=r=>{let e=ls(r),[t,n]=Ol(e),[i,s]=Ol(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Lc(t,i,o,e)},PA=(r,e)=>r===e?!0:r.code===e.code&&r.size===e.size&&fA(r.bytes,e.bytes),Lc=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}}});var b8,w8,E8=je(()=>{Ml();b8=({name:r,code:e,encode:t})=>new w8(r,e,t),w8=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?Jo(this.code,t):t.then(n=>Jo(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var v8={};Ae(v8,{sha256:()=>Pz,sha512:()=>kz});var NA,Pz,kz,LA=je(()=>{E8();NA=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Pz=b8({name:"sha2-256",code:18,encode:NA("SHA-256")}),kz=b8({name:"sha2-512",code:19,encode:NA("SHA-512")})});var x8={};Ae(x8,{identity:()=>Oz});var OA,Nz,BA,Lz,Oz,MA=je(()=>{so();Ml();OA=0,Nz="identity",BA=ls,Lz=r=>Jo(OA,BA(r)),Oz={code:OA,name:Nz,encode:BA,digest:Lz}});var UA=je(()=>{so()});var wpe,bpe,FA=je(()=>{wpe=new TextEncoder,bpe=new TextDecoder});var Xt,Uz,Fz,Kz,Ul,qz,KA,qA,B1,M1,Vz,zz,Hz,VA=je(()=>{O1();Ml();p8();h8();so();Xt=class{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:M1,byteLength:M1,code:B1,version:B1,multihash:B1,bytes:B1,_baseCache:M1,asCID:M1})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:t}=this;if(e!==Ul)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qz)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Xt.createV0(t)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Jo(e,t);return Xt.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&PA(this.multihash,e.multihash)}toString(e){let{bytes:t,version:n,_baseCache:i}=this;switch(n){case 0:return Fz(t,i,e||ki.encoder);default:return Kz(t,i,e||Pc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return zz(/^0\.0/,Hz),!!(e&&(e[qA]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof Xt)return e;if(e!=null&&e.asCID===e){let{version:t,code:n,multihash:i,bytes:s}=e;return new Xt(t,n,i,s||KA(t,n,i.bytes))}else if(e!=null&&e[qA]===!0){let{version:t,multihash:n,code:i}=e,s=CA(n);return Xt.create(t,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(t!==Ul)throw new Error(`Version 0 CID must use dag-pb (code: ${Ul}) block encoding`);return new Xt(e,t,n,n.bytes)}case 1:{let i=KA(e,t,n.bytes);return new Xt(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return Xt.create(0,Ul,e)}static createV1(e,t){return Xt.create(1,e,t)}static decode(e){let[t,n]=Xt.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=Xt.inspectBytes(e),n=t.size-t.multihashSize,i=ls(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new Lc(t.multihashCode,t.digestSize,s,i);return[t.version===0?Xt.createV0(o):Xt.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=Ol(e.subarray(t));return t+=f,h},i=n(),s=Ul;if(i===18?(i=0,t=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=Uz(e,t),s=Xt.decode(i);return s._baseCache.set(n,e),s}},Uz=(r,e)=>{switch(r[0]){case"Q":{let t=e||ki;return[ki.prefix,t.decode(`${ki.prefix}${r}`)]}case ki.prefix:{let t=e||ki;return[ki.prefix,t.decode(r)]}case Pc.prefix:{let t=e||Pc;return[Pc.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)]}}},Fz=(r,e,t)=>{let{prefix:n}=t;if(n!==ki.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},Kz=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},Ul=112,qz=18,KA=(r,e,t)=>{let n=Nc(r),i=n+Nc(e),s=new Uint8Array(i+t.byteLength);return kc(r,s,0),kc(e,s,n),s.set(t,i),s},qA=Symbol.for("@ipld/js-cid/CID"),B1={writable:!1,configurable:!1,enumerable:!0},M1={writable:!1,enumerable:!1,configurable:!1},Vz="0.0.0-dev",zz=(r,e)=>{if(r.test(Vz))console.warn(e);else throw new Error(e)},Hz=`CID.isCID(v) is deprecated and will be removed in the next major release.
|
|
39
|
+
Following code pattern:
|
|
40
|
+
|
|
41
|
+
if (CID.isCID(value)) {
|
|
42
|
+
doSomethingWithCID(value)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
Is replaced with:
|
|
46
|
+
|
|
47
|
+
const cid = CID.asCID(value)
|
|
48
|
+
if (cid) {
|
|
49
|
+
// Make sure to use cid instead of value
|
|
50
|
+
doSomethingWithCID(cid)
|
|
51
|
+
}
|
|
52
|
+
`});var zA=je(()=>{VA();O1();so();E8();Ml()});var _8,Ipe,HA=je(()=>{yA();wA();bA();EA();vA();h8();xA();p8();_A();AA();LA();MA();UA();FA();zA();_8={...s8,...o8,...a8,...c8,...u8,...l8,...f8,...d8,...m8,...g8},Ipe={...v8,...x8}});function Oc(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var U1=je(()=>{});function F1(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Oc(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var S8=je(()=>{U1()});function GA(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var $A,A8,$z,K1,R8=je(()=>{HA();S8();$A=GA("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),A8=GA("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=F1(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$z={utf8:$A,"utf-8":$A,hex:_8.base16,latin1:A8,ascii:A8,binary:A8,..._8},K1=$z});var WA={};Ae(WA,{toString:()=>Gz});function Gz(r,e="utf8"){let t=K1[e];if(!t)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 YA=je(()=>{R8()});var QA={};Ae(QA,{fromString:()=>Wz});function Wz(r,e="utf8"){let t=K1[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Oc(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var XA=je(()=>{R8();U1()});var jA={};Ae(jA,{concat:()=>Yz});function Yz(r,e){e||(e=r.reduce((i,s)=>i+s.length,0));let t=F1(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return Oc(t)}var ZA=je(()=>{S8();U1()});var T8=T((Kpe,iR)=>{"use strict";var JA=XS(),Bc=aA(),{names:Fl}=uA(),{toString:q1}=(YA(),oh(WA)),{fromString:Qz}=(XA(),oh(QA)),{concat:Xz}=(ZA(),oh(jA)),Mc={};for(let r in Fl){let e=r;Mc[Fl[e]]=e}Object.freeze(Mc);function jz(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return q1(r,"base16")}function Zz(r){return Qz(r,"base16")}function Jz(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return q1(JA.encode("base58btc",r)).slice(1)}function eH(r){let e=r instanceof Uint8Array?q1(r):r;return JA.decode("z"+e)}function eR(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=Bc.decode(r);if(!rR(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(Bc.decode.bytes);let t=Bc.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(Bc.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${q1(r,"base16")}`);return{code:e,name:Mc[e],length:t,digest:r}}function tH(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=tR(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let i=Bc.encode(n),s=Bc.encode(t);return Xz([i,s,r],i.length+s.length+r.length)}function tR(r){let e=r;if(typeof r=="string"){if(Fl[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=Fl[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Mc[e]===void 0&&!I8(e))throw new Error(`Unrecognized function code: ${e}`);return e}function I8(r){return r>0&&r<16}function rR(r){return!!(I8(r)||Mc[r])}function nR(r){eR(r)}function rH(r){return nR(r),r.subarray(0,2)}iR.exports={names:Fl,codes:Mc,toHexString:jz,fromHexString:Zz,toB58String:Jz,fromB58String:eH,decode:eR,encode:tH,coerceCode:tR,isAppCode:I8,validate:nR,prefix:rH,isValidCode:rR}});var mR=T(G1=>{"use strict";Object.defineProperty(G1,"__esModule",{value:!0});var L8=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}))}}},$1=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new L8;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:s=>i.push(s),stop:()=>i.stop(),fail:s=>i.fail(s),on:(s,o)=>{i.eventHandlers[s]=o}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};G1.EventIterator=$1;G1.default=$1});var gR=T(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var O8=mR();Kl.EventIterator=O8.EventIterator;function fH(r,e,t){return new O8.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}Kl.subscribe=fH;Kl.default=O8.EventIterator});var M8=T((b2e,SR)=>{"use strict";var dH=typeof navigator<"u"&&navigator.product==="ReactNative";function pH(){return dH?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}var ql=self.URL,_R=pH(),B8=class{constructor(e="",t=_R){this.super=new ql(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 ql.createObjectURL(e)}static revokeObjectURL(e){ql.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}};function mH(r){if(typeof r=="string")return new ql(r).toString();if(!(r instanceof ql)){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+"//":"",s=r.host||"",o=r.hostname||"",a=r.search||(r.query?"?"+r.query:""),c=r.hash||"",u=r.pathname||"",l=r.path||u+a;return`${i}${e||t}${s||o+n}${l}${c}`}}SR.exports={URLWithLegacySupport:B8,URLSearchParams:self.URLSearchParams,defaultBase:_R,format:mH}});var IR=T((E2e,RR)=>{"use strict";var{URLWithLegacySupport:AR,format:gH}=M8();RR.exports=(r,e={},t={},n)=>{let i=e.protocol?e.protocol.replace(":",""):"http";i=(t[i]||n||i)+":";let s;try{s=new AR(r)}catch{s={}}let o=Object.assign({},e,{protocol:i||s.protocol,host:e.host||s.host});return new AR(r,gH(o)).toString()}});var DR=T((v2e,TR)=>{"use strict";var{URLWithLegacySupport:yH,format:wH,URLSearchParams:bH,defaultBase:EH}=M8(),vH=IR();TR.exports={URL:yH,URLSearchParams:bH,format:wH,relative:vH,defaultBase:EH}});var UR=T((D2e,MR)=>{function SH(){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)}MR.exports=SH});var oI=T(Q8=>{"use strict";Object.defineProperty(Q8,"__esModule",{value:!0});function LH(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}Q8.isSerializableHash=LH});var cI=T(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Ni=oI(),OH=E0(),BH=Di(),aI=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<n.length;i++)n[i]^=54;this._inner.update(n);for(var i=0;i<n.length;i++)n[i]^=106;this._outer.update(n),Ni.isSerializableHash(this._inner)&&Ni.isSerializableHash(this._outer)&&(this._innerKeyedState=this._inner.saveState(),this._outerKeyedState=this._outer.saveState()),BH.wipe(n)}return r.prototype.reset=function(){if(!Ni.isSerializableHash(this._inner)||!Ni.isSerializableHash(this._outer))throw new Error("hmac: can't reset() because hash doesn't implement restoreState()");return this._inner.restoreState(this._innerKeyedState),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.clean=function(){Ni.isSerializableHash(this._inner)&&this._inner.cleanSavedState(this._innerKeyedState),Ni.isSerializableHash(this._outer)&&this._outer.cleanSavedState(this._outerKeyedState),this._inner.clean(),this._outer.clean()},r.prototype.update=function(e){return this._inner.update(e),this},r.prototype.finish=function(e){return this._finished?(this._outer.finish(e),this):(this._inner.finish(e),this._outer.update(e.subarray(0,this.digestLength)).finish(e),this._finished=!0,this)},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(!Ni.isSerializableHash(this._inner))throw new Error("hmac: can't saveState() because hash doesn't implement it");return this._inner.saveState()},r.prototype.restoreState=function(e){if(!Ni.isSerializableHash(this._inner)||!Ni.isSerializableHash(this._outer))throw new Error("hmac: can't restoreState() because hash doesn't implement it");return this._inner.restoreState(e),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},r.prototype.cleanSavedState=function(e){if(!Ni.isSerializableHash(this._inner))throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it");this._inner.cleanSavedState(e)},r}();Hl.HMAC=aI;function MH(r,e,t){var n=new aI(r,e);n.update(t);var i=n.digest();return n.clean(),i}Hl.hmac=MH;Hl.equal=OH.equal});var hI=T(X8=>{"use strict";Object.defineProperty(X8,"__esModule",{value:!0});var uI=cI(),lI=Di(),UH=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 s=uI.hmac(this._hash,n,t);this._hmac=new uI.HMAC(e,s),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<t.length;n++)this._bufpos===this._buffer.length&&this._fillBuffer(),t[n]=this._buffer[this._bufpos++];return t},r.prototype.clean=function(){this._hmac.clean(),lI.wipe(this._buffer),lI.wipe(this._counter),this._bufpos=0},r}();X8.HKDF=UH});var dI=T(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var rd=al(),td=Di();co.DIGEST_LENGTH=32;co.BLOCK_SIZE=64;var fI=function(){function r(){this.digestLength=co.DIGEST_LENGTH,this.blockSize=co.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(){td.wipe(this._buffer),td.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._bufferLength<this.blockSize&&t>0;)this._buffer[this._bufferLength++]=e[n++],t--;this._bufferLength===this.blockSize&&(j8(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(n=j8(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,s=t<<3,o=t%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a<o-8;a++)this._buffer[a]=0;rd.writeUint32BE(i,this._buffer,o-8),rd.writeUint32BE(s,this._buffer,o-4),j8(this._temp,this._state,this._buffer,0,o),this._finished=!0}for(var a=0;a<this.digestLength/4;a++)rd.writeUint32BE(this._state[a],e,a*4);return this},r.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},r.prototype.saveState=function(){if(this._finished)throw new Error("SHA256: cannot save finished state");return{state:new Int32Array(this._state),buffer:this._bufferLength>0?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){td.wipe(e.state),e.buffer&&td.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},r}();co.SHA256=fI;var FH=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 j8(r,e,t,n,i){for(;i>=64;){for(var s=e[0],o=e[1],a=e[2],c=e[3],u=e[4],l=e[5],h=e[6],f=e[7],d=0;d<16;d++){var p=n+d*4;r[d]=rd.readUint32BE(t,p)}for(var d=16;d<64;d++){var m=r[d-2],g=(m>>>17|m<<32-17)^(m>>>19|m<<32-19)^m>>>10;m=r[d-15];var y=(m>>>7|m<<32-7)^(m>>>18|m<<32-18)^m>>>3;r[d]=(g+r[d-7]|0)+(y+r[d-16]|0)}for(var d=0;d<64;d++){var g=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&l^~u&h)|0)+(f+(FH[d]+r[d]|0)|0)|0,y=((s>>>2|s<<32-2)^(s>>>13|s<<32-13)^(s>>>22|s<<32-22))+(s&o^s&a^o&a)|0;f=h,h=l,l=u,u=c+g|0,c=a,a=o,o=s,s=g+y|0}e[0]+=s,e[1]+=o,e[2]+=a,e[3]+=c,e[4]+=u,e[5]+=l,e[6]+=h,e[7]+=f,n+=64,i-=64}return n}function KH(r){var e=new fI;e.update(r);var t=e.digest();return e.clean(),t}co.hash=KH});var BI=T((zme,OI)=>{"use strict";function QH(r){return r>=55296&&r<=56319}function XH(r){return r>=56320&&r<=57343}OI.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,s=0,o,a,c=0;c<i;c+=1){if(o=t.charCodeAt(c),a=t[c],QH(o)&&XH(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var UI=T((Hme,MI)=>{"use strict";function jH(r){return r>=55296&&r<=56319}function ZH(r){return r>=56320&&r<=57343}MI.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,s=null,o=0;o<t;o++)i=e.charCodeAt(o),ZH(i)?s!=null&&jH(s)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),s=i;return n}});var KI=T(($me,FI)=>{"use strict";var JH=BI(),e$=UI();FI.exports=JH.bind(null,e$)});var zI=T((Gme,VI)=>{"use strict";var t$=KI(),r$=/[\/\?<>\\:\*\|"]/g,n$=/[\x00-\x1f\x80-\x9f]/g,i$=/^\.+$/,s$=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,o$=/[\. ]+$/;function qI(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(r$,e).replace(n$,e).replace(i$,e).replace(s$,e).replace(o$,e);return t$(t,255)}VI.exports=function(r,e){var t=e&&e.replacement||"",n=qI(r,t);return t===""?n:qI(n,"")}});var $I=T((Wme,HI)=>{"use strict";HI.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var jI=T((QI,XI)=>{"use strict";var ld=$I(),{hasOwnProperty:WI}=Object.prototype,{propertyIsEnumerable:a$}=Object,qc=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),c$=QI,GI={concatArrays:!1,ignoreUndefined:!1},hd=r=>{let e=[];for(let t in r)WI.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)a$.call(r,n)&&e.push(n)}return e};function Vc(r){return Array.isArray(r)?u$(r):ld(r)?l$(r):r}function u$(r){let e=r.slice(0,0);return hd(r).forEach(t=>{qc(e,t,Vc(r[t]))}),e}function l$(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return hd(r).forEach(t=>{qc(e,t,Vc(r[t]))}),e}var YI=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?qc(r,i,o5(r[i],e[i],n)):qc(r,i,Vc(e[i])))}),r),h$=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)WI.call(s,a)&&(o.push(String(a)),s===r?qc(n,i++,s[a]):qc(n,i++,Vc(s[a])));n=YI(n,s,hd(s).filter(a=>!o.includes(a)),t)}),n};function o5(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?h$(r,e,t):!ld(e)||!ld(r)?Vc(e):YI(r,e,hd(e),t)}XI.exports=function(...r){let e=o5(Vc(GI),this!==c$&&this||{},GI),t={_:{}};for(let n of r)if(n!==void 0){if(!ld(n))throw new TypeError("`"+n+"` is not an Option Object");t=o5(t,{_:n},e)}return t._}});var yT=T((F8e,gT)=>{"use strict";gT.exports=mT;var b$=vp(),ho=mT.prototype,E$=new Date%1e9;function v$(){return(Math.random()*1e9>>>0)+E$++}function mT(r){r=r||{},this.id=r.id||v$(),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)}ho.has=function(r){return r in this._lookup};ho.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};ho.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};ho.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};ho.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};ho.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=b$(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};ho.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};ho.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 XT=T((Nye,QT)=>{function Mn(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}QT.exports=Mn;Mn.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Mn.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Mn.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Mn.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Mn.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Mn.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Mn.prototype.start=Mn.prototype.try;Mn.prototype.errors=function(){return this._errors};Mn.prototype.attempts=function(){return this._attempts};Mn.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(r[s]||0)+1;r[s]=o,o>=t&&(e=i,t=o)}return e}});var jT=T(ua=>{var Y$=XT();ua.operation=function(r){var e=ua.timeouts(r);return new Y$(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};ua.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,o){return s-o}),n};ua.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};ua.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var s=t[i],o=r[s];r[s]=function(c){var u=ua.operation(e),l=Array.prototype.slice.call(arguments,1),h=l.pop();l.push(function(f){u.retry(f)||(f&&(arguments[0]=u.mainError()),h.apply(this,arguments))}),u.attempt(function(){c.apply(r,l)})}.bind(r,o),r[s].options=e}}});var JT=T((Oye,ZT)=>{ZT.exports=jT()});var uG={};Ae(uG,{createHelia:()=>cG});var ah={};Ae(ah,{abortedError:()=>TD,closeFailedError:()=>_D,deleteFailedError:()=>RD,getFailedError:()=>AD,hasFailedError:()=>ID,notFoundError:()=>Yd,openFailedError:()=>xD,putFailedError:()=>SD});var Ui=F(ps(),1);function xD(r){return r=r??new Error("Open failed"),(0,Ui.default)(r,"ERR_OPEN_FAILED")}function _D(r){return r=r??new Error("Close failed"),(0,Ui.default)(r,"ERR_CLOSE_FAILED")}function SD(r){return r=r??new Error("Put failed"),(0,Ui.default)(r,"ERR_PUT_FAILED")}function AD(r){return r=r??new Error("Get failed"),(0,Ui.default)(r,"ERR_GET_FAILED")}function RD(r){return r=r??new Error("Delete failed"),(0,Ui.default)(r,"ERR_DELETE_FAILED")}function ID(r){return r=r??new Error("Has failed"),(0,Ui.default)(r,"ERR_HAS_FAILED")}function Yd(r){return r=r??new Error("Not Found"),(0,Ui.default)(r,"ERR_NOT_FOUND")}function TD(r){return r=r??new Error("Aborted"),(0,Ui.default)(r,"ERR_ABORTED")}var tu=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async delete(e,t){await Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Jd={};Ae(Jd,{base32:()=>Yt,base32hex:()=>MD,base32hexpad:()=>FD,base32hexpadupper:()=>KD,base32hexupper:()=>UD,base32pad:()=>OD,base32padupper:()=>BD,base32upper:()=>LD,base32z:()=>qD});function DD(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var E=(b-y)*l+1>>>0,R=new Uint8Array(E);y!==b;){for(var v=p[y],_=0,I=E-1;(v!==0||_<g)&&I!==-1;I--,_++)v+=256*R[I]>>>0,R[I]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=_,y++}for(var P=E-g;P!==E&&R[P]===0;)P++;for(var M=c.repeat(m);P<E;++P)M+=r.charAt(R[P]);return M}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,E=new Uint8Array(b);p[m];){var R=t[p.charCodeAt(m)];if(R===255)return;for(var v=0,_=b-1;(R!==0||v<y)&&_!==-1;_--,v++)R+=a*E[_]>>>0,E[_]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");y=v,m++}if(p[m]!==" "){for(var I=b-y;I!==b&&E[I]===0;)I++;for(var P=new Uint8Array(g+(b-I)),M=g;I!==b;)P[M++]=E[I++];return P}}}function d(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var CD=DD,PD=CD,r6=PD;var pG=new Uint8Array(0);var n6=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0},Fi=r=>{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 i6=r=>new TextEncoder().encode(r),s6=r=>new TextDecoder().decode(r);var Qd=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")}},Xd=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 a6(this,e)}},jd=class{constructor(e){this.decoders=e}or(e){return a6(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`)}},a6=(r,e)=>new jd({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),Zd=class{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Qd(e,t,n),this.decoder=new Xd(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},la=({name:r,prefix:e,encode:t,decode:n})=>new Zd(r,e,t,n),ms=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=r6(t,e);return la({prefix:r,name:e,encode:n,decode:s=>Fi(i(s))})},kD=(r,e,t,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let h=i[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ND=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<<t-o]),n)for(;s.length*t&7;)s+="=";return s},Dt=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>la({prefix:e,name:r,encode(i){return ND(i,n,t)},decode(i){return kD(i,n,t,r)}});var Yt=Dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LD=Dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),OD=Dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),BD=Dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),MD=Dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),UD=Dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),FD=Dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),KD=Dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qD=Dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ch=85;var VD=l6,c6=128,zD=127,HD=~zD,$D=Math.pow(2,31);function l6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=$D;)e[t++]=r&255|c6,r/=128;for(;r&HD;)e[t++]=r&255|c6,r>>>=7;return e[t]=r|0,l6.bytes=t-n+1,e}var GD=tp,WD=128,u6=127;function tp(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw tp.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&u6)<<i:(o&u6)*Math.pow(2,i),i+=7}while(o>=WD);return tp.bytes=s-n,t}var YD=Math.pow(2,7),QD=Math.pow(2,14),XD=Math.pow(2,21),jD=Math.pow(2,28),ZD=Math.pow(2,35),JD=Math.pow(2,42),eC=Math.pow(2,49),tC=Math.pow(2,56),rC=Math.pow(2,63),nC=function(r){return r<YD?1:r<QD?2:r<XD?3:r<jD?4:r<ZD?5:r<JD?6:r<eC?7:r<tC?8:r<rC?9:10},iC={encode:VD,decode:GD,encodingLength:nC},sC=iC,ru=sC;var nu=(r,e=0)=>[ru.decode(r,e),ru.decode.bytes],ha=(r,e,t=0)=>(ru.encode(r,e,t),e),fa=r=>ru.encodingLength(r);var Fn={};Ae(Fn,{Digest:()=>mo,create:()=>Un,decode:()=>ui,equals:()=>rp});var Un=(r,e)=>{let t=e.byteLength,n=fa(r),i=n+fa(t),s=new Uint8Array(i+t);return ha(r,s,0),ha(t,s,n),s.set(e,i),new mo(r,t,e,s)},ui=r=>{let e=Fi(r),[t,n]=nu(e),[i,s]=nu(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new mo(t,i,o,e)},rp=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&n6(r.bytes,t.bytes)}},mo=class{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var np={};Ae(np,{base58btc:()=>me,base58flickr:()=>oC});var me=ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oC=ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var h6=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return cC(t,ip(r),e||me.encoder);default:return uC(t,ip(r),e||Yt.encoder)}};var f6=new WeakMap,ip=r=>{let e=f6.get(r);if(e==null){let t=new Map;return f6.set(r,t),t}return e},ee=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!==iu)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==lC)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ee.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=Un(e,t);return ee.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 ee.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&rp(e.multihash,n.multihash)}toString(e){return h6(this,e)}toJSON(){return{"/":h6(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 ee)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new ee(n,i,s,o||d6(n,i,s.bytes))}else if(t[hC]===!0){let{version:n,multihash:i,code:s}=t,o=ui(i);return ee.create(n,s,o)}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!==iu)throw new Error(`Version 0 CID must use dag-pb (code: ${iu}) block encoding`);return new ee(e,t,n,n.bytes)}case 1:{let i=d6(e,t,n.bytes);return new ee(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return ee.create(0,iu,e)}static createV1(e,t){return ee.create(1,e,t)}static decode(e){let[t,n]=ee.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=ee.inspectBytes(e),n=t.size-t.multihashSize,i=Fi(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new mo(t.multihashCode,t.digestSize,s,i);return[t.version===0?ee.createV0(o):ee.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=nu(e.subarray(t));return t+=f,h},i=n(),s=iu;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=aC(e,t),s=ee.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ip(s).set(n,e),s}},aC=(r,e)=>{switch(r[0]){case"Q":{let t=e||me;return[me.prefix,t.decode(`${me.prefix}${r}`)]}case me.prefix:{let t=e||me;return[me.prefix,t.decode(r)]}case Yt.prefix:{let t=e||Yt;return[Yt.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)]}}},cC=(r,e,t)=>{let{prefix:n}=t;if(n!==me.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i},uC=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i},iu=112,lC=18,d6=(r,e,t)=>{let n=fa(r),i=n+fa(e),s=new Uint8Array(i+t.byteLength);return ha(r,s,0),ha(e,s,n),s.set(t,i),s},hC=Symbol.for("@ipld/js-cid/CID");var su=class extends tu{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Yt.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Yt.encode(e.multihash.bytes));if(t==null)throw Yd();return t}has(e){return this.data.has(Yt.encode(e.multihash.bytes))}async delete(e){this.data.delete(Yt.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:ee.createV1(ch,ui(Yt.decode(e))),block:t}}};var NG={...ah};var p6=F(ps(),1);function lh(r){return r=r??new Error("Not Found"),(0,p6.default)(r,"ERR_NOT_FOUND")}var m6=(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 sp={};Ae(sp,{identity:()=>fC});var fC=la({prefix:"\0",name:"identity",encode:r=>s6(r),decode:r=>i6(r)});var op={};Ae(op,{base2:()=>dC});var dC=Dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ap={};Ae(ap,{base8:()=>pC});var pC=Dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cp={};Ae(cp,{base10:()=>mC});var mC=ms({prefix:"9",name:"base10",alphabet:"0123456789"});var up={};Ae(up,{base16:()=>gC,base16upper:()=>yC});var gC=Dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yC=Dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lp={};Ae(lp,{base36:()=>au,base36upper:()=>wC});var au=ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wC=ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hp={};Ae(hp,{base64:()=>Ki,base64pad:()=>bC,base64url:()=>EC,base64urlpad:()=>vC});var Ki=Dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),bC=Dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),EC=Dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vC=Dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fp={};Ae(fp,{base256emoji:()=>RC});var g6=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}"),xC=g6.reduce((r,e,t)=>(r[t]=e,r),[]),_C=g6.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function SC(r){return r.reduce((e,t)=>(e+=xC[t],e),"")}function AC(r){let e=[];for(let t of r){let n=_C[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var RC=la({prefix:"\u{1F680}",name:"base256emoji",encode:SC,decode:AC});var gp={};Ae(gp,{sha256:()=>Pe,sha512:()=>mp});var pp=({name:r,code:e,encode:t})=>new dp(r,e,t),dp=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?Un(this.code,t):t.then(n=>Un(this.code,n))}else throw Error("Unknown type, must be binary type")}};var w6=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Pe=pp({name:"sha2-256",code:18,encode:w6("SHA-256")}),mp=pp({name:"sha2-512",code:19,encode:w6("SHA-512")});var yp={};Ae(yp,{identity:()=>li});var b6=0,IC="identity",E6=Fi,TC=r=>Un(b6,E6(r)),li={code:b6,name:IC,encode:E6,digest:TC};var QG=new TextEncoder,XG=new TextDecoder;var En={...sp,...op,...ap,...cp,...up,...Jd,...lp,...np,...hp,...fp},tW={...gp,...yp};function qi(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Vi(r=0){return globalThis.Buffer?.alloc!=null?qi(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Tr(r=0){return globalThis.Buffer?.allocUnsafe!=null?qi(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function x6(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var v6=x6("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),wp=x6("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Tr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),CC={utf8:v6,"utf-8":v6,hex:En.base16,latin1:wp,ascii:wp,binary:wp,...En},hh=CC;function B(r,e="utf8"){let t=hh[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)}function q(r,e="utf8"){let t=hh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qi(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var zi="/",_6=new TextEncoder().encode(zi),fh=_6[0],ve=class{constructor(e,t){if(typeof e=="string")this._buf=q(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==fh)throw new Error("Invalid key")}toString(e="utf8"){return B(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ve(e.join(zi))}static random(){return new ve(m6().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new ve(e):typeof e.uint8Array=="function"?new ve(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=_6),this._buf[0]!==fh){let e=new Uint8Array(this._buf.byteLength+1);e.fill(fh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===fh;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let s=t[i],o=n[i];if(s<o)return!0;if(s>o)return!1}return t.length<n.length}reverse(){return ve.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(zi).slice(1)}type(){return PC(this.baseNamespace())}name(){return kC(this.baseNamespace())}instance(e){return new ve(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(zi)||(e+=zi),e+=this.type(),new ve(e)}parent(){let e=this.list();return e.length===1?new ve(zi):new ve(e.slice(0,-1).join(zi))}child(e){return this.toString()===zi?e:e.toString()===zi?this:new ve(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return ve.withNamespaces([...this.namespaces(),...NC(e.map(t=>t.namespaces()))])}};function PC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function kC(r){let e=r.split(":");return e[e.length-1]}function NC(r){return[].concat(...r)}var S6="SHARDING";function OC(r){return r[Symbol.asyncIterator]!=null}function BC(r){if(OC(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var bp=BC;function MC(r){return r[Symbol.asyncIterator]!=null}function UC(r,e){return MC(r)?async function*(){yield*(await bp(r)).sort(e)}():function*(){yield*bp(r).sort(e)}()}var dh=UC;function FC(r){return r[Symbol.asyncIterator]!=null}function KC(r){if(FC(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yr=KC;function qC(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}}}var da=qC;function VC(r){return r[Symbol.asyncIterator]!=null}function zC(r,e){if(VC(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=da(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let o=e;return function*(){s===!0&&(yield n);for(let a of t)o(a)&&(yield a)}()}var Fr=zC;function HC(r){return r[Symbol.asyncIterator]!=null}function $C(r,e){return HC(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var gs=$C;var Hi=class{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 n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await 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 Yr(this.putMany(e,n)),e=[],await Yr(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){let i=e.prefix;n=Fr(n,s=>s.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Fr(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>dh(i,s),n)),e.offset!=null){let i=0,s=e.offset;n=Fr(n,()=>i++>=s)}return e.limit!=null&&(n=gs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=Fr(n,s=>s.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,s)=>Fr(i,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,s)=>dh(i,s),n)),e.offset!=null){let i=e.offset,s=0;n=Fr(n,()=>s++>=i)}return e.limit!=null&&(n=gs(n,e.limit)),n}};var go=class extends Hi{constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw lh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new ve(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new ve(e)}};function GC(r){return r[Symbol.asyncIterator]!=null}function WC(r,e){if(GC(r))return async function*(){for await(let a of r)yield e(a)}();let t=da(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of t)yield e(a)}();let o=e;return function*(){yield s;for(let a of t)yield o(a)}()}var Kn=WC;var ph=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}},pa=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ph(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ph(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?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function tt(r={}){return R6(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 A6(r={}){return R6(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 R6(r,e){e=e??{};let t=e.onEnd,n=new pa,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((m,g)=>{s=y=>{s=null,n.push(y);try{m(r(n))}catch(b){g(b)}return i}}):r(n),c=m=>s!=null?s(m):(n.push(m),i),u=m=>(n=new pa,s!=null?s({error:m}):(n.push({error:m}),i)),l=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:m})},h=m=>o?i:(o=!0,m!=null?u(m):c({done:!0})),f=()=>(n=new pa,h(),{done:!0}),d=m=>(h(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:f,throw:d,push:l,end:h,get readableLength(){return n.size}},t==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),i},get readableLength(){return p.readableLength}},i}function YC(r){return r[Symbol.asyncIterator]!=null}function QC(...r){let e=[];for(let t of r)YC(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=tt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let i of n)t.push(i)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var jt=QC;function be(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ep(r)){let n=r;r=()=>n.source}else if(T6(r)||I6(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ep(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ep(t[n])&&(t[n]=jC(t[n]));return XC(...t)}var XC=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},I6=r=>r?.[Symbol.asyncIterator]!=null,T6=r=>r?.[Symbol.iterator]!=null,Ep=r=>r==null?!1:r.sink!=null&&r.source!=null,jC=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=tt({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let i,s=r.source;if(I6(s))i=async function*(){yield*s,n.end()};else if(T6(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return jt(n,i())}return r.source};var nY=new ve(S6);var vn=F(xp(),1);vn.default.formatters.b=r=>r==null?"undefined":me.baseEncode(r);vn.default.formatters.t=r=>r==null?"undefined":Yt.baseEncode(r);vn.default.formatters.m=r=>r==null?"undefined":Ki.baseEncode(r);vn.default.formatters.p=r=>r==null?"undefined":r.toString();vn.default.formatters.c=r=>r==null?"undefined":r.toString();vn.default.formatters.k=r=>r==null?"undefined":r.toString();function fP(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 D(r){let e=fP(`${r}:trace`);return vn.default.enabled(`${r}:trace`)&&vn.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,vn.default)(`${r}:trace`)),Object.assign((0,vn.default)(r),{error:(0,vn.default)(`${r}:error`),trace:e})}var vY=D("datastore:core:tiered");function it(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}function dP(r){return r[Symbol.asyncIterator]!=null}function pP(r,e){if(dP(r))return async function*(){for await(let a of r)await e(a),yield a}();let t=da(r),{value:n,done:i}=t.next();if(i===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t)await e(a),yield a}();let o=e;return function*(){yield n;for(let a of t)o(a),yield a}()}var cu=pP;var _p=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 hi(r){let{name:e,metrics:t}=r,n;return t!=null?n=new _p({name:e,metrics:t}):n=new Map,n}var yh=class extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=yh.code,this.type=yh.type}},Xr=yh;br(Xr,"code","ABORT_ERR"),br(Xr,"type","aborted");var w=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var Kg=F(G6(),1);function pe(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var wo=class{_refCounter;cid;priority;wantType;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 <key: ${this.cid.toString(me)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(e){return this._refCounter===e._refCounter&&this.cid.equals(e.cid)&&this.priority===e.priority&&this.wantType===e.wantType}};var ys=class{entry;cancel;sendDontHave;constructor(e,t,n,i,s){this.entry=new wo(e,t,n),this.cancel=!!i,this.sendDontHave=!!s}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(me)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(e){return this.cancel===e.cancel&&this.sendDontHave===e.sendDontHave&&this.wantType===e.wantType&&this.entry.equals(e.entry)}};var xn=(r,e)=>{let t=["bitswap"];return e!=null&&t.push(e),r!=null&&t.push(`${r.toString().slice(0,8)}`),D(t.join(":"))};var wh=(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&&!pe(n,i)||n instanceof ys&&i instanceof ys&&!n.equals(i))return!1}return!0};var uu=F(bo(),1);function qP(r){let e=new Uint8Array(r.reduce((n,i)=>n+uu.default.encodingLength(i),0)),t=0;for(let n of r)e=uu.encode(n,e,t),t+=uu.default.encodingLength(n);return e}var rg=qP;var Gp=F(Up(),1),Bg=F(Tg(),1),Mg=F(vo(),1),Wp=F($p(),1),Ug=F(Og(),1);function XP(){Mg.default._configure(),Gp.default._configure(Bg.default),Wp.default._configure(Ug.default)}XP();var Fg=["uint64","int64","sint64","fixed64","sfixed64"];function jP(r){for(let e of Fg){if(r[e]==null)continue;let t=r[e];r[e]=function(){return BigInt(t.call(this).toString())}}return r}function Yp(r){return jP(new Gp.default(r))}function ZP(r){for(let e of Fg){if(r[e]==null)continue;let t=r[e];r[e]=function(n){return t.call(this,n.toString())}}return r}function Qp(){return ZP(Wp.default.create())}function ne(r,e){let t=Yp(r instanceof Uint8Array?r:r.subarray());return e.decode(t)}function ie(r,e){let t=Qp();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var ba;(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"})(ba||(ba={}));function _h(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ht(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return _h("enum",ba.VARINT,t,n)}function se(r,e){return _h("message",ba.LENGTH_DELIMITED,r,e)}var Kr;(function(r){let e;(function(a){let c;(function(f){f.Block="Block",f.Have="Have"})(c=a.WantType||(a.WantType={}));let u;(function(f){f[f.Block=0]="Block",f[f.Have=1]="Have"})(u||(u={})),function(f){f.codec=()=>Ht(u)}(c=a.WantType||(a.WantType={}));let l;(function(f){let d;f.codec=()=>(d==null&&(d=se((p,m,g={})=>{g.lengthDelimited!==!1&&m.fork(),p.block!=null&&p.block.byteLength>0&&(m.uint32(10),m.bytes(p.block)),p.priority!=null&&p.priority!==0&&(m.uint32(16),m.int32(p.priority)),p.cancel!=null&&p.cancel!==!1&&(m.uint32(24),m.bool(p.cancel)),p.wantType!=null&&u[p.wantType]!==0&&(m.uint32(32),r.Wantlist.WantType.codec().encode(p.wantType,m)),p.sendDontHave!=null&&p.sendDontHave!==!1&&(m.uint32(40),m.bool(p.sendDontHave)),g.lengthDelimited!==!1&&m.ldelim()},(p,m)=>{let g={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},y=m==null?p.len:p.pos+m;for(;p.pos<y;){let b=p.uint32();switch(b>>>3){case 1:g.block=p.bytes();break;case 2:g.priority=p.int32();break;case 3:g.cancel=p.bool();break;case 4:g.wantType=r.Wantlist.WantType.codec().decode(p);break;case 5:g.sendDontHave=p.bool();break;default:p.skipType(b&7);break}}return g})),d),f.encode=p=>ie(p,f.codec()),f.decode=p=>ne(p,f.codec())})(l=a.Entry||(a.Entry={}));let h;a.codec=()=>(h==null&&(h=se((f,d,p={})=>{if(p.lengthDelimited!==!1&&d.fork(),f.entries!=null)for(let m of f.entries)d.uint32(10),r.Wantlist.Entry.codec().encode(m,d);f.full!=null&&f.full!==!1&&(d.uint32(16),d.bool(f.full)),p.lengthDelimited!==!1&&d.ldelim()},(f,d)=>{let p={entries:[],full:!1},m=d==null?f.len:f.pos+d;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:p.entries.push(r.Wantlist.Entry.codec().decode(f,f.uint32()));break;case 2:p.full=f.bool();break;default:f.skipType(g&7);break}}return p})),h),a.encode=f=>ie(f,a.codec()),a.decode=f=>ne(f,a.codec())})(e=r.Wantlist||(r.Wantlist={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=se((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.prefix!=null&&u.prefix.byteLength>0&&(l.uint32(10),l.bytes(u.prefix)),u.data!=null&&u.data.byteLength>0&&(l.uint32(18),l.bytes(u.data)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={prefix:new Uint8Array(0),data:new Uint8Array(0)},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.prefix=u.bytes();break;case 2:h.data=u.bytes();break;default:u.skipType(d&7);break}}return h})),c),a.encode=u=>ie(u,a.codec()),a.decode=u=>ne(u,a.codec())})(t=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let i;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(i||(i={})),function(a){a.codec=()=>Ht(i)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=se((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.cid!=null&&u.cid.byteLength>0&&(l.uint32(10),l.bytes(u.cid)),u.type!=null&&i[u.type]!==0&&(l.uint32(16),r.BlockPresenceType.codec().encode(u.type,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={cid:new Uint8Array(0),type:n.Have},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.cid=u.bytes();break;case 2:h.type=r.BlockPresenceType.codec().decode(u);break;default:u.skipType(d&7);break}}return h})),c),a.encode=u=>ie(u,a.codec()),a.decode=u=>ne(u,a.codec())})(s=r.BlockPresence||(r.BlockPresence={}));let o;r.codec=()=>(o==null&&(o=se((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let l of a.blocks)c.uint32(18),c.bytes(l);if(a.payload!=null)for(let l of a.payload)c.uint32(26),r.Block.codec().encode(l,c);if(a.blockPresences!=null)for(let l of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(l,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),u.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let u={blocks:[],payload:[],blockPresences:[],pendingBytes:0},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:u.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:u.blocks.push(a.bytes());break;case 3:u.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:u.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:u.pendingBytes=a.int32();break;default:a.skipType(h&7);break}}return u})),o),r.encode=a=>ie(a,r.codec()),r.decode=a=>ne(a,r.codec())})(Kr||(Kr={}));var pi=class{full;wantlist;blocks;blockPresences;pendingBytes;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,s){n==null&&(n=pi.WantType.Block);let o=e.toString(me),a=this.wantlist.get(o);a!=null?(a.wantType===n&&(a.priority=t),i===!0&&(a.cancel=!!i),s===!0&&(a.sendDontHave=!!s),n===pi.WantType.Block&&a.wantType===pi.WantType.Have&&(a.wantType=n)):this.wantlist.set(o,new ys(e,t,n,i,s))}addBlock(e,t){let n=e.toString(me);this.blocks.set(n,t)}addHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,pi.BlockPresenceType.Have)}addDontHave(e){let t=e.toString(me);this.blockPresences.has(t)||this.blockPresences.set(t,pi.BlockPresenceType.DontHave)}cancel(e){let t=e.toString(me);this.wantlist.delete(t),this.addEntry(e,0,pi.WantType.Block,!0,!1)}setPendingBytes(e){this.pendingBytes=e}serializeToBitswap100(){return Kr.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),cancel:!!e.cancel,wantType:Kr.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}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},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[t,n]of this.blocks.entries()){let i=ee.parse(t),s=i.version,o=i.code,a=i.multihash.code,c=i.multihash.digest.length,u=rg([s,o,a,c]);e.payload.push({prefix:u,data:n})}for(let[t,n]of this.blockPresences)e.blockPresences.push({cid:ee.parse(t).bytes,type:n});return this.pendingBytes>0&&(e.pendingBytes=this.pendingBytes),Kr.encode(e)}equals(e){return!(this.full!==e.full||this.pendingBytes!==e.pendingBytes||!wh(this.wantlist,e.wantlist)||!wh(this.blocks,e.blocks)||!wh(this.blockPresences,e.blockPresences))}get[Symbol.toStringTag](){let e=Array.from(this.wantlist.keys()),t=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${e}, blocks: ${t}>`}},Bt=pi;br(Bt,"Entry",ys),br(Bt,"WantType",{Block:Kr.Wantlist.WantType.Block,Have:Kr.Wantlist.WantType.Have}),br(Bt,"BlockPresenceType",{Have:Kr.BlockPresenceType.Have,DontHave:Kr.BlockPresenceType.DontHave}),br(Bt,"deserialize",async(e,t)=>{let n=Kr.decode(e),i=n.wantlist?.full===!0,s=new pi(i);return n.wantlist?.entries.forEach(o=>{if(o.block==null)return;let a=ee.decode(o.block);s.addEntry(a,o.priority??0,o.wantType,!!o.cancel,!!o.sendDontHave)}),n.blockPresences.forEach(o=>{if(o.cid==null)return;let a=ee.decode(o.cid);o.type===pi.BlockPresenceType.Have?s.addHave(a):s.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async o=>{let a=await Pe.digest(o),c=ee.createV0(a);s.addBlock(c,o)})),s):(n.payload.length>0&&(await Promise.all(n.payload.map(async o=>{if(o.prefix==null||o.data==null)return;let a=(0,Kg.default)(o.prefix),c=a[0],u=a[1],l=a[2],h=l===Pe.code?Pe:await t?.getHasher(l);if(h==null)throw new w("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let f=await h.digest(o.data),d=ee.create(c,u,f);s.addBlock(d,o.data)})),s.setPendingBytes(n.pendingBytes)),s)}),br(Bt,"blockPresenceSize",e=>e.bytes.length+1);var qg={Block:Kr.Wantlist.WantType.Block,Have:Kr.Wantlist.WantType.Have},JP=(r,e)=>Array.prototype.slice.call(e,0).sort((t,n)=>{let i=r(t),s=r(n);return i<s?-1:i>s?1:0}),$i=class{set;_stats;constructor(e,t){this.set=t!=null?hi({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(me),s=this.set.get(i);s!=null?(s.inc(),s.priority=t,s.wantType===qg.Have&&n===qg.Block&&(s.wantType=n)):(this.set.set(i,new wo(e,t,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(e){let t=e.toString(me),n=this.set.get(t);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(t),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(e){this.set.has(e)&&this.set.delete(e)}forEach(e){this.set.forEach(e)}entries(){return this.set.entries()}sortedEntries(){return new Map(JP(e=>e[1].key,Array.from(this.set.entries())))}contains(e){let t=e.toString(me);return this.set.has(t)}get(e){let t=e.toString(me);return this.set.get(t)}};br($i,"Entry",wo);var Sh=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(e){this.partner=e,this.wantlist=new $i,this.exchangeCount=0,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 fu=class extends Map{_cmp;_keys;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<this._keys.length;n++){if(this._keys[t+n]===e)return t+n;if(this._keys[t-n]===e)return t-n}return-1}_find(e){let t=0,n=this._keys.length;for(;t<n;){let i=t+n>>>1,s=this._kCmp(this._keys[i],e);if(s<0)t=i+1;else if(s>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=this){if(e!=null)for(let n of this._keys){let i=this.get(n);if(i==null)throw new Error("Value cannot be undefined");e.apply(t,[[n,i]])}}_defaultSort(e,t){return e[0]<t[0]?-1:t[0]<e[0]?1:0}_kCmp(e,t){return this._cmp([e,this.get(e)],[t,this.get(t)])}};var ek={hasNewInfo(){return!1},merge(){}},Ah=class{_taskMerger;_byPeer;constructor(e=ek){this._taskMerger=e,this._byPeer=new fu([],Rh.compare)}pushTasks(e,t){let n=this._byPeer.get(e.toString());n==null&&(n=new Rh(e,this._taskMerger)),n.pushTasks(t),this._byPeer.set(e.toString(),n)}popTasks(e){let t=this._head();if(t===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:i}=t.popTasks(e);if(n.length===0)return{tasks:n,pendingSize:i};let s=t.peerId;return t.isIdle()?this._byPeer.delete(s.toString()):this._byPeer.update(0),{peerId:s,tasks:n,pendingSize:i}}_head(){if(this._byPeer.size!==0)for(let[,e]of this._byPeer)return e}remove(e,t){this._byPeer.get(t.toString())?.remove(e)}tasksDone(e,t){let n=this._byPeer.get(e.toString());if(n==null)return;let i=this._byPeer.indexOf(e.toString());for(let s of t)n.taskDone(s);this._byPeer.update(i)}},Rh=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(e,t){this.peerId=e,this._taskMerger=t,this._activeTotalSize=0,this._pending=new Xp,this._active=new Set}pushTasks(e){for(let t of e)this._pushTask(t)}_pushTask(e){if(!this._taskHasMoreInfoThanActiveTasks(e))return;let t=this._pending.get(e.topic);if(t!=null){e.priority>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 s=0;s<i.length&&t<e;s++){let o=i[s];n.push(o),t+=o.size,this._pending.delete(o.topic),this._activeTotalSize+=o.size,this._active.add(o)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(e){this._active.has(e)&&(this._activeTotalSize-=e.size,this._active.delete(e))}remove(e){this._pending.delete(e)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(e,t){return e[1]._pending.length===0?1:t[1]._pending.length===0?-1:e[1]._activeTotalSize===t[1]._activeTotalSize?t[1]._pending.length-e[1]._pending.length:e[1]._activeTotalSize-t[1]._activeTotalSize}},Xp=class{_tasks;constructor(){this._tasks=new fu([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((e,t)=>e+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==null)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 Vg={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 zg=Bt.WantType,tk=16*1024,rk=1024,Ih=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(e,t,n,i,s,o={}){this._log=xn(e,"engine"),this.blockstore=t,this.network=n,this._stats=i,this._opts=this._processOpts(o),this.ledgerMap=hi({name:"ipfs_bitswap_ledger_map",metrics:s.metrics}),this._running=!1,this._requestQueue=new Ah(Vg)}_processOpts(e){return{maxSizeReplaceHasWithBlock:rk,targetMessageSize:tk,...e}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(e=>{this._log.error("error processing stats",e)})})}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 Bt(!1);i.setPendingBytes(n);let s=[],o=new Map;for(let c of t){let u=ee.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(s.push(u),o.set(c.topic,c.data)):i.addHave(u):i.addDontHave(u)}let a=await this._getBlocks(s);for(let[c,u]of o){let l=ee.parse(c),h=a.get(c);h!=null?i.addBlock(l,h):u.sendDontHave&&i.addDontHave(l)}if(i.empty){e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks();return}try{e!=null&&await this.network.sendMessage(e,i);for(let[c,u]of a.entries())e!=null&&this.messageSent(e,ee.parse(c),u)}catch(c){this._log.error(c)}e!=null&&this._requestQueue.tasksDone(e,t),this._scheduleProcessTasks()}wantlistForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(e){let t=e.toString(),n=this.ledgerMap.get(t);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.partner)}receivedBlocks(e){if(e.length!==0){for(let t of this.ledgerMap.values())for(let{cid:n,block:i}of e){let s=t.wantlistContains(n);if(s==null)continue;let o=i.length,a=this._sendAsBlock(s.wantType,o),c=o;a||(c=Bt.blockPresenceSize(s.cid)),this._requestQueue.pushTasks(t.partner,[{topic:s.cid.toString(me),priority:s.priority,size:c,data:{blockSize:o,isWantBlock:a,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 $i),this._updateBlockAccounting(t.blocks,n),t.wantlist.size===0){this._scheduleProcessTasks();return}let i=[],s=[];t.wantlist.forEach(o=>{o.cancel?(n.cancelWant(o.cid),i.push(o.cid)):(n.wants(o.cid,o.priority,o.wantType),s.push(o))}),this._cancelWants(e,i),await this._addWants(e,s),this._scheduleProcessTasks()}_cancelWants(e,t){for(let n of t)this._requestQueue.remove(n.toString(me),e)}async _addWants(e,t){let n=await this._getBlockSizes(t.map(s=>s.cid)),i=[];for(let s of t){let o=s.cid.toString(me),a=n.get(o);if(a==null)s.sendDontHave&&i.push({topic:o,priority:s.priority,size:Bt.blockPresenceSize(s.cid),data:{isWantBlock:s.wantType===zg.Block,blockSize:0,haveBlock:!1,sendDontHave:s.sendDontHave}});else{let c=this._sendAsBlock(s.wantType,a),u=a;c||(u=Bt.blockPresenceSize(s.cid)),i.push({topic:o,priority:s.priority,size:u,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:s.sendDontHave}})}this._requestQueue.pushTasks(e,i)}}_sendAsBlock(e,t){return e===zg.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(me),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!=null)return n;let i=new Sh(e);return this.ledgerMap.set(t,i),this._stats!=null&&this._stats.push(t,"peerCount",1),i}start(){this._running=!0}stop(){this._running=!1}};var Th=Symbol.for("@libp2p/topology");function Hg(r){return r!=null&&!!r[Th]}var $g=()=>{},jp=class{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??$g,this.onDisconnect=e.onDisconnect??$g}get[Symbol.toStringTag](){return Th.toString()}get[Th](){return!0}async setRegistrar(e){this.registrar=e}disconnect(e){this.onDisconnect(e)}};function Es(r){return new jp(r)}var du=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Gg(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 lt(r,e,t){let n=t??{},i=Gg(r);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:h}=n;throw new du(l,h)}let u=new Promise((l,h)=>{o=()=>{let{abortMessage:f,abortCode:d}=n;h(new du(f,d))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(r),typeof i.return=="function")try{let h=i.return();h instanceof Promise&&h.catch(f=>{n.onReturnError!=null&&n.onReturnError(f)})}catch(h){n.onReturnError!=null&&n.onReturnError(h)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function nk(r,e,t){return n=>r(lt(n,e,t))}function Er(r,e,t){return{sink:nk(r.sink,e,{...t,onAbort:void 0}),source:lt(r.source,e,t)}}function he(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=Tr(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return qi(t)}var Yg=Symbol.for("@achingbrain/uint8arraylist");function Wg(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(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Dh(r){return!!r?.[Yg]}var j=class{constructor(...e){Object.defineProperty(this,Yg,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Dh(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(Dh(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=Wg(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Wg(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Dh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)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 he(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:he(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new j;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(o);break}let h=e-a;n.push(o.subarray(h,h+(t-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Dh(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 s=256,o=new Int32Array(s);for(let h=0;h<s;h++)o[h]=-1;for(let h=0;h<i;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let f=u;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){l=Math.max(1,f-a[d]);break}}if(l===0)return h}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=Tr(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=Vi(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=Vi(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=Vi(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=Tr(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=Vi(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=Vi(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=Vi(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=Vi(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=Vi(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof j)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!pe(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new j;return n.bufs=e,t==null&&(t=e.reduce((i,s)=>i+s.byteLength,0)),n.length=t,n}};function Ch(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 Qg=4294967296,jr=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 jr(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 jr(t,n)}toBytes(e,t=0){let n=Ch(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 jr;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>Qg&&(i=0,++n>Qg&&(n=0))),new jr(n,i)}static fromNumber(e){if(e===0)return new jr;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 jr(i,n)}static fromBytes(e,t=0){let n=Ch(e),i=new jr,s=0;if(e.length-t>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>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;s=0}else for(;s<4;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(n.get(t)&127)<<s*7)>>>0,n.get(t++)<128)return i}if(e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}else if(t<e.byteLength)for(;s<5;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(n.get(t)&127)<<s*7+3)>>>0,n.get(t++)<128)return i}throw RangeError("invalid varint encoding")}};var ik=Math.pow(2,7),sk=Math.pow(2,14),ok=Math.pow(2,21),ak=Math.pow(2,28),ck=Math.pow(2,35),uk=Math.pow(2,42),lk=Math.pow(2,49),hk=Math.pow(2,56),fk=Math.pow(2,63),ct={encodingLength(r){return r<ik?1:r<sk?2:r<ok?3:r<ak?4:r<ck?5:r<uk?6:r<lk?7:r<hk?8:r<fk?9:10},encode(r,e,t=0){if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Tr(ct.encodingLength(r))),jr.fromNumber(r).toBytes(e,t),e},decode(r,e=0){return jr.fromBytes(r,e).toNumber(!0)}};function Ph(r){return r[Symbol.asyncIterator]!=null}var kh=r=>{let e=ct.encodingLength(r),t=Tr(e);return ct.encode(r,t),kh.bytes=e,t};kh.bytes=0;function Et(r,e){e=e??{};let t=e.lengthEncoder??kh;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Ph(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Et.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??kh;return new j(t(r.byteLength),r)};var Ea=F(ps(),1);var dk=8,pk=1024*1024*4,_o;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_o||(_o={}));var Zp=r=>{let e=ct.decode(r);return Zp.bytes=ct.encodingLength(e),e};Zp.bytes=0;function Ct(r,e){let t=new j,n=_o.LENGTH,i=-1,s=e?.lengthDecoder??Zp,o=e?.maxLengthLength??dk,a=e?.maxDataLength??pk;function*c(){for(;t.byteLength>0;){if(n===_o.LENGTH)try{if(i=s(t),i<0)throw(0,Ea.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Ea.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=_o.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw(0,Ea.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===_o.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=_o.LENGTH}}}return Ph(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Ea.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Ea.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Ct.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Ct(n,{...e??{},onLength:s=>{t=s}})};var Ze=class extends Event{constructor(e,t){super(e),this.detail=t}};var oy=F(ry(),1);var ny=Math.pow(2,31)-1,iy=1e3,sy=1;var t2="/ipfs/bitswap/1.0.0",r2="/ipfs/bitswap/1.1.0",n2="/ipfs/bitswap/1.2.0",wk=1024,bk=1024,Ek=3e4,Lh=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(e,t,n,i={}){this._log=xn(e.peerId,"network"),this._libp2p=e,this._bitswap=t,this._protocols=[t2],i.b100Only!==!0&&(this._protocols.unshift(r2),this._protocols.unshift(n2)),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??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=i.maxInboundStreams??wk,this._maxOutboundStreams=i.maxOutboundStreams??bk,this._incomingStreamTimeout=i.incomingStreamTimeout??Ek}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let e=Es({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(e){if(!this._running)return;let{stream:t,connection:n}=e,i=new oy.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",t.stat.protocol,n.remotePeer),await be(lt(t.source,i.signal),s=>Ct(s),async s=>{for await(let o of s){try{let a=await Bt.deserialize(o.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,a)}catch(a){this._bitswap._receiveError(a);break}i.reset()}})}).catch(s=>{this._log(s),t.abort(s)}).finally(()=>{i.clear(),t.close()})}_onPeerConnect(e){this._bitswap._onPeerConnected(e)}_onPeerDisconnect(e){this._bitswap._onPeerDisconnected(e)}findProviders(e,t={}){return t.onProgress?.(new Ze("bitswap:network:find-providers",e)),this._libp2p.contentRouting.findProviders(e,t)}async findAndConnect(e,t){await Yr(gs(Kn(this.findProviders(e,t),async n=>this.connectTo(n.id,t).catch(i=>{this._log.error(i)})),3)).catch(n=>{this._log.error(n)})}async provide(e,t={}){t.onProgress?.(new Ze("bitswap:network:provide",e)),await this._libp2p.contentRouting.provide(e,t)}async sendMessage(e,t,n={}){if(!this._running)throw new Error("network isn't running");let i=e.toString();this._log("sendMessage to %s",i,t),n.onProgress?.(new Ze("bitswap:network:send-wantlist",e)),await this._writeMessage(e,t,n),this._updateSentStats(e,t.blocks)}async connectTo(e,t={}){if(!this._running)throw new Error("network isn't running");return t.onProgress?.(new Ze("bitswap:network:dial",e)),this._libp2p.dial(e,t)}_updateSentStats(e,t){let n=e.toString();if(this._stats!=null){for(let i of t.values())this._stats.push(n,"dataSent",i.length);this._stats.push(n,"blocksSent",t.size)}}async _writeMessage(e,t,n={}){let i=await this._libp2p.dialProtocol(e,[n2,r2,t2]);try{let s;switch(i.stat.protocol){case t2:s=t.serializeToBitswap100();break;case r2:case n2:s=t.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${i.stat.protocol}`)}await be([s],o=>Et(o),i)}catch(s){n.onProgress?.(new Ze("bitswap:network:send-wantlist:error",{peer:e,error:s})),this._log(s)}finally{i.close()}}};var by=F(Zr(),1);var yy=r=>`unwant:${B(r.multihash.bytes,"base64")}`,wy=r=>`block:${B(r.multihash.bytes,"base64")}`,Mh=class extends by.EventEmitter{_log;constructor(e){super(),this.setMaxListeners(iy),this._log=xn(e,"notif")}hasBlock(e,t){let n=wy(e);this._log(n),this.emit(n,t)}async wantBlock(e,t={}){if(e==null)throw new Error("Not a valid cid");let n=wy(e),i=yy(e);return this._log(`wantBlock:${e}`),new Promise((s,o)=>{let a=()=>{this.removeListener(n,c),t.onProgress?.(new Ze("bitswap:want-block:unwant",e)),o(new Error(`Block for ${e} unwanted`))},c=u=>{this.removeListener(i,a),t.onProgress?.(new Ze("bitswap:want-block:block",e)),s(u)};this.once(i,a),this.once(n,c),t.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(i,a),o(new Error(`Want for ${e} aborted`))})})}unwantBlock(e){let t=yy(e);this._log(t),this.emit(t)}};var Ay=F(Zr(),1);var _y=F(Zr(),1),s2=F(xy(),1),mu=class extends _y.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;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,s2.default)(i)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&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!=null&&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=void 0,this._queue.length>0){let e;for(;this._queue.length>0;){let t=e=this._queue.shift();t!=null&&this._applyOp(t)}e!=null&&this._updateFrequency(e[2]),this.emit("update",this._stats)}}_updateFrequency(e){let t=e-this._frequencyLastTime;t>0&&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 s=i/t*1e3,o=this._movingAverages[e];o==null&&(o=this._movingAverages[e]={}),this._options.movingAverageIntervals.forEach(a=>{let c=o[a];c==null&&(c=o[a]=(0,s2.default)(a)),c.push(n,s)})}_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]==null&&(this._frequencyAccumulators[t]=0),this._frequencyAccumulators[t]+=n}};var Sy={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Uh=class extends Ay.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(e,t=[],n=Sy){super();let i=Object.assign({},Sy,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 mu(t,i),this._global.on("update",s=>this.emit("update",s)),this._peers=hi({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=e.toString();return this._peers.get(t)}push(e,t,n){if(this._enabled&&(this._global.push(t,n),e!=null)){let i=this._peers.get(e);i==null&&(i=new mu(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!=null&&(n.stop(),this._peers.delete(t))}};var Ry=Tk;function Tk(r,e,t){var n=null,i=null,s=function(){n&&(clearTimeout(n),i=null,n=null)},o=function(){var c=i;s(),c&&c()},a=function(){if(!e)return r.apply(this,arguments);var c=this,u=arguments,l=t&&!n;if(s(),i=function(){r.apply(c,u)},n=setTimeout(function(){if(n=null,!l){var h=i;return i=null,h()}},e),l)return i()};return a.cancel=s,a.flush=o,a}var Fh=class{peerId;refcnt;network;_entries;_log;constructor(e,t,n){this.peerId=t,this.network=n,this.refcnt=1,this._entries=[],this._log=xn(e,"msgqueue"),this.sendEntries=Ry(this.sendEntries.bind(this),sy)}addMessage(e,t={}){e.empty||this.send(e,t)}addEntries(e,t={}){this._entries=this._entries.concat(e),this.sendEntries(t)}sendEntries(e={}){if(this._entries.length===0)return;let t=new Bt(!1);this._entries.forEach(n=>{n.cancel===!0?t.cancel(n.cid):t.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(t,e)}async send(e,t={}){try{await this.network.connectTo(this.peerId,t)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,e,t).catch(n=>{this._log.error("send error",n)})}};var Kh=class{peers;wantlist;network;_peerId;_log;constructor(e,t,n,i){this.peers=hi({name:"ipfs_bitswap_want_manager_peers",metrics:i.metrics}),this.wantlist=new $i(n,i),this.network=t,this._peerId=e,this._log=xn(e,"want")}_addEntries(e,t,n,i={}){let s=e.map((o,a)=>new Bt.Entry(o,ny-a,Bt.WantType.Block,t));s.forEach(o=>{o.cancel?n===!0?this.wantlist.removeForce(o.cid.toString(me)):this.wantlist.remove(o.cid):(this._log("adding to wantlist"),this.wantlist.add(o.cid,o.priority))});for(let o of this.peers.values())o.addEntries(s,i)}_startPeerHandler(e){let t=this.peers.get(e.toString());if(t!=null){t.refcnt++;return}t=new Fh(this._peerId,e,this.network);let n=new Bt(!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!=null&&(t.refcnt--,!(t.refcnt>0)&&this.peers.delete(e.toString()))}wantBlocks(e,t={}){this._addEntries(e,!1,!1,t),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 Dk={async getHasher(){throw new Error("Not implemented")}},Ck={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:Dk,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},Pk=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],qh=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(e,t,n={}){this._libp2p=e,this._log=xn(this.peerId),n=Object.assign({},Ck,n),this.stats=new Uh(e,Pk,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new Lh(e,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=t,this.engine=new Ih(this.peerId,t,this.network,this.stats,e),this.wm=new Kh(this.peerId,this.network,this.stats,e),this.notifications=new Mh(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,s]of t.blocks.entries()){let o=ee.parse(i);n.push({wasWanted:this.wm.wantlist.contains(o),cid:o,data:s})}this.wm.cancelWants(n.filter(({wasWanted:i})=>i).map(({cid:i})=>i)),await Promise.all(n.map(async({cid:i,wasWanted:s,data:o})=>{await this._handleReceivedBlock(e,i,o,s)}))}async _handleReceivedBlock(e,t,n,i){this._log("received block");let s=await this.blockstore.has(t);this._updateReceiveCounters(e.toString(),t,n,s),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",e)}_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 want(e,t={}){let n=async(c,u)=>(this.wm.wantBlocks([c],u),this.notifications.wantBlock(c,u)),i=!1,s=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(h=>{this._log.error(h)})),await n(c,u)}},o=new AbortController,a=it([o.signal,t.signal]);try{return await Promise.race([this.notifications.wantBlock(e,{...t,signal:a}),s(e,{...t,signal:a})])}finally{o.abort(),a.clear()}}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.notify(e,t)}async*putMany(e,t){yield*this.blockstore.putMany(cu(e,({cid:n,block:i})=>{this.notify(n,i)}),t)}notify(e,t,n={}){this.notifications.hasBlock(e,t),this.engine.receivedBlocks([{cid:e,block:t}]),this.network.provide(e,n).catch(i=>{this._log.error("Failed to provide: %s",i.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}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}};var Iy=(r,e,t={})=>new qh(r,e,t);var kk=["string","number","bigint","symbol"],Nk=["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 Ty(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(kk.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(Lk(r))return"Buffer";let t=Ok(r);return t||"Object"}function Lk(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Ok(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Nk.includes(e))return e}var S=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.major<e.major?-1:this.major>e.major?1:0}};S.uint=new S(0,"uint",!0);S.negint=new S(1,"negint",!0);S.bytes=new S(2,"bytes",!0);S.string=new S(3,"string",!0);S.array=new S(4,"array",!1);S.map=new S(5,"map",!1);S.tag=new S(6,"tag",!1);S.float=new S(7,"float",!0);S.false=new S(7,"false",!0);S.true=new S(7,"true",!0);S.null=new S(7,"null",!0);S.undefined=new S(7,"undefined",!0);S.break=new S(7,"break",!0);var U=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 xa=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Bk=new TextDecoder,Mk=new TextEncoder;function Vh(r){return xa&&globalThis.Buffer.isBuffer(r)}function gu(r){return r instanceof Uint8Array?Vh(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ky=xa?(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?Bk.decode(r.subarray(e,t)):Cy(r,e,t),zh=xa?r=>r.length>64?globalThis.Buffer.from(r):Dy(r):r=>r.length>64?Mk.encode(r):Dy(r),mi=r=>Uint8Array.from(r),_a=xa?(r,e,t)=>Vh(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ny=xa?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),gu(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},Ly=xa?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Oy(r,e){if(Vh(r)&&Vh(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Dy(r,e=1/0){let t,n=r.length,i=null,s=[];for(let o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function Cy(r,e,t){let n=[];for(;e<t;){let i=r[e],s=null,o=i>239?4:i>223?3:i>191?2:1;if(e+o<=t){let a,c,u,l;switch(o){case 1:i<128&&(s=i);break;case 2:a=r[e+1],(a&192)===128&&(l=(i&31)<<6|a&63,l>127&&(s=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)&&(s=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&&(s=l))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=o}return o2(n)}var Py=4096;function o2(r){let e=r.length;if(e<=Py)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Py));return t}var Uk=256,yu=class{constructor(e=Uk){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ly(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=_a(n,0,this.cursor)}else t=Ny(this.chunks,this.cursor);return e&&this.reset(),t}};var Y="CBOR decode error:",Sa="CBOR encode error:",wu=[];wu[23]=1;wu[24]=2;wu[25]=3;wu[26]=5;wu[27]=9;function Gi(r,e,t){if(r.length-e<t)throw new Error(`${Y} not enough data for type`)}var Jt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Jr(r,e,t){Gi(r,e,1);let n=r[e];if(t.strict===!0&&n<Jt[0])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function en(r,e,t){Gi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Jt[1])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function tn(r,e,t){Gi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Jt[2])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);return n}function rn(r,e,t){Gi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&s<Jt[3])throw new Error(`${Y} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Y} integers outside of the safe integer range are not supported`)}function By(r,e,t,n){return new U(S.uint,Jr(r,e+1,n),2)}function My(r,e,t,n){return new U(S.uint,en(r,e+1,n),3)}function Uy(r,e,t,n){return new U(S.uint,tn(r,e+1,n),5)}function Fy(r,e,t,n){return new U(S.uint,rn(r,e+1,n),9)}function Sn(r,e){return cr(r,0,e.value)}function cr(r,e,t){if(t<Jt[0]){let n=Number(t);r.push([e|n])}else if(t<Jt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Jt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Jt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Jt[4]){let i=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,r.push(i)}else throw new Error(`${Y} encountered BigInt larger than allowable range`)}}Sn.encodedSize=function(e){return cr.encodedSize(e.value)};cr.encodedSize=function(e){return e<Jt[0]?1:e<Jt[1]?2:e<Jt[2]?3:e<Jt[3]?5:9};Sn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Ky(r,e,t,n){return new U(S.negint,-1-Jr(r,e+1,n),2)}function qy(r,e,t,n){return new U(S.negint,-1-en(r,e+1,n),3)}function Vy(r,e,t,n){return new U(S.negint,-1-tn(r,e+1,n),5)}var a2=BigInt(-1),zy=BigInt(1);function Hy(r,e,t,n){let i=rn(r,e+1,n);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new U(S.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Y} integers outside of the safe integer range are not supported`);return new U(S.negint,a2-BigInt(i),9)}function Hh(r,e){let t=e.value,n=typeof t=="bigint"?t*a2-zy:t*-1-1;cr(r,e.type.majorEncoded,n)}Hh.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*a2-zy:t*-1-1;return n<Jt[0]?1:n<Jt[1]?2:n<Jt[2]?3:n<Jt[3]?5:9};Hh.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function bu(r,e,t,n){Gi(r,e,t+n);let i=_a(r,e+t,e+t+n);return new U(S.bytes,i,t+n)}function $y(r,e,t,n){return bu(r,e,1,t)}function Gy(r,e,t,n){return bu(r,e,2,Jr(r,e+1,n))}function Wy(r,e,t,n){return bu(r,e,3,en(r,e+1,n))}function Yy(r,e,t,n){return bu(r,e,5,tn(r,e+1,n))}function Qy(r,e,t,n){let i=rn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer bytes lengths not supported`);return bu(r,e,9,i)}function $h(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===S.string?zh(r.value):r.value),r.encodedBytes}function Aa(r,e){let t=$h(e);cr(r,e.type.majorEncoded,t.length),r.push(t)}Aa.encodedSize=function(e){let t=$h(e);return cr.encodedSize(t.length)+t.length};Aa.compareTokens=function(e,t){return Kk($h(e),$h(t))};function Kk(r,e){return r.length<e.length?-1:r.length>e.length?1:Oy(r,e)}function Eu(r,e,t,n,i){let s=t+n;Gi(r,e,s);let o=new U(S.string,ky(r,e+t,e+s),s);return i.retainStringBytes===!0&&(o.byteValue=_a(r,e+t,e+s)),o}function Xy(r,e,t,n){return Eu(r,e,1,t,n)}function jy(r,e,t,n){return Eu(r,e,2,Jr(r,e+1,n),n)}function Zy(r,e,t,n){return Eu(r,e,3,en(r,e+1,n),n)}function Jy(r,e,t,n){return Eu(r,e,5,tn(r,e+1,n),n)}function e7(r,e,t,n){let i=rn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer string lengths not supported`);return Eu(r,e,9,i,n)}var t7=Aa;function Ra(r,e,t,n){return new U(S.array,n,t)}function r7(r,e,t,n){return Ra(r,e,1,t)}function n7(r,e,t,n){return Ra(r,e,2,Jr(r,e+1,n))}function i7(r,e,t,n){return Ra(r,e,3,en(r,e+1,n))}function s7(r,e,t,n){return Ra(r,e,5,tn(r,e+1,n))}function o7(r,e,t,n){let i=rn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer array lengths not supported`);return Ra(r,e,9,i)}function a7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Ra(r,e,1,1/0)}function Gh(r,e){cr(r,S.array.majorEncoded,e.value)}Gh.compareTokens=Sn.compareTokens;Gh.encodedSize=function(e){return cr.encodedSize(e.value)};function Ia(r,e,t,n){return new U(S.map,n,t)}function c7(r,e,t,n){return Ia(r,e,1,t)}function u7(r,e,t,n){return Ia(r,e,2,Jr(r,e+1,n))}function l7(r,e,t,n){return Ia(r,e,3,en(r,e+1,n))}function h7(r,e,t,n){return Ia(r,e,5,tn(r,e+1,n))}function f7(r,e,t,n){let i=rn(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Y} 64-bit integer map lengths not supported`);return Ia(r,e,9,i)}function d7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return Ia(r,e,1,1/0)}function Wh(r,e){cr(r,S.map.majorEncoded,e.value)}Wh.compareTokens=Sn.compareTokens;Wh.encodedSize=function(e){return cr.encodedSize(e.value)};function p7(r,e,t,n){return new U(S.tag,t,1)}function m7(r,e,t,n){return new U(S.tag,Jr(r,e+1,n),2)}function g7(r,e,t,n){return new U(S.tag,en(r,e+1,n),3)}function y7(r,e,t,n){return new U(S.tag,tn(r,e+1,n),5)}function w7(r,e,t,n){return new U(S.tag,rn(r,e+1,n),9)}function Yh(r,e){cr(r,S.tag.majorEncoded,e.value)}Yh.compareTokens=Sn.compareTokens;Yh.encodedSize=function(e){return cr.encodedSize(e.value)};var Gk=20,Wk=21,Yk=22,Qk=23;function b7(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(S.null,null,1):new U(S.undefined,void 0,1)}function E7(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Y} indefinite length items not allowed`);return new U(S.break,void 0,1)}function c2(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Y} Infinity values are not supported`)}return new U(S.float,r,e)}function v7(r,e,t,n){return c2(u2(r,e+1),3,n)}function x7(r,e,t,n){return c2(l2(r,e+1),5,n)}function _7(r,e,t,n){return c2(I7(r,e+1),9,n)}function Qh(r,e,t){let n=e.value;if(n===!1)r.push([S.float.majorEncoded|Gk]);else if(n===!0)r.push([S.float.majorEncoded|Wk]);else if(n===null)r.push([S.float.majorEncoded|Yk]);else if(n===void 0)r.push([S.float.majorEncoded|Qk]);else{let i,s=!1;(!t||t.float64!==!0)&&(A7(n),i=u2(zn,1),n===i||Number.isNaN(n)?(zn[0]=249,r.push(zn.slice(0,3)),s=!0):(R7(n),i=l2(zn,1),n===i&&(zn[0]=250,r.push(zn.slice(0,5)),s=!0))),s||(Xk(n),i=I7(zn,1),zn[0]=251,r.push(zn.slice(0,9)))}}Qh.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){A7(n);let i=u2(zn,1);if(n===i||Number.isNaN(n))return 3;if(R7(n),i=l2(zn,1),n===i)return 5}return 9};var S7=new ArrayBuffer(9),An=new DataView(S7,1),zn=new Uint8Array(S7,0);function A7(r){if(r===1/0)An.setUint16(0,31744,!1);else if(r===-1/0)An.setUint16(0,64512,!1);else if(Number.isNaN(r))An.setUint16(0,32256,!1);else{An.setFloat32(0,r);let e=An.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)An.setUint16(0,31744,!1);else if(t===0)An.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?An.setUint16(0,0):i<-14?An.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):An.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function u2(r,e){if(r.length-e<2)throw new Error(`${Y} 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,s;return n===0?s=i*2**-24:n!==31?s=(i+1024)*2**(n-25):s=i===0?1/0:NaN,t&32768?-s:s}function R7(r){An.setFloat32(0,r,!1)}function l2(r,e){if(r.length-e<4)throw new Error(`${Y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Xk(r){An.setFloat64(0,r,!1)}function I7(r,e){if(r.length-e<8)throw new Error(`${Y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Qh.compareTokens=Sn.compareTokens;function Ye(r,e,t){throw new Error(`${Y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Xh(r){return()=>{throw new Error(`${Y} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=Ye;K[24]=By;K[25]=My;K[26]=Uy;K[27]=Fy;K[28]=Ye;K[29]=Ye;K[30]=Ye;K[31]=Ye;for(let r=32;r<=55;r++)K[r]=Ye;K[56]=Ky;K[57]=qy;K[58]=Vy;K[59]=Hy;K[60]=Ye;K[61]=Ye;K[62]=Ye;K[63]=Ye;for(let r=64;r<=87;r++)K[r]=$y;K[88]=Gy;K[89]=Wy;K[90]=Yy;K[91]=Qy;K[92]=Ye;K[93]=Ye;K[94]=Ye;K[95]=Xh("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=Xy;K[120]=jy;K[121]=Zy;K[122]=Jy;K[123]=e7;K[124]=Ye;K[125]=Ye;K[126]=Ye;K[127]=Xh("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=r7;K[152]=n7;K[153]=i7;K[154]=s7;K[155]=o7;K[156]=Ye;K[157]=Ye;K[158]=Ye;K[159]=a7;for(let r=160;r<=183;r++)K[r]=c7;K[184]=u7;K[185]=l7;K[186]=h7;K[187]=f7;K[188]=Ye;K[189]=Ye;K[190]=Ye;K[191]=d7;for(let r=192;r<=215;r++)K[r]=p7;K[216]=m7;K[217]=g7;K[218]=y7;K[219]=w7;K[220]=Ye;K[221]=Ye;K[222]=Ye;K[223]=Ye;for(let r=224;r<=243;r++)K[r]=Xh("simple values are not supported");K[244]=Ye;K[245]=Ye;K[246]=Ye;K[247]=b7;K[248]=Xh("simple values are not supported");K[249]=v7;K[250]=x7;K[251]=_7;K[252]=Ye;K[253]=Ye;K[254]=Ye;K[255]=E7;var Hn=[];for(let r=0;r<24;r++)Hn[r]=new U(S.uint,r,1);for(let r=-1;r>=-24;r--)Hn[31-r]=new U(S.negint,r,1);Hn[64]=new U(S.bytes,new Uint8Array(0),1);Hn[96]=new U(S.string,"",1);Hn[128]=new U(S.array,0,1);Hn[160]=new U(S.map,0,1);Hn[244]=new U(S.false,!1,1);Hn[245]=new U(S.true,!0,1);Hn[246]=new U(S.null,null,1);function T7(r){switch(r.type){case S.false:return mi([244]);case S.true:return mi([245]);case S.null:return mi([246]);case S.bytes:return r.value.length?void 0:mi([64]);case S.string:return r.value===""?mi([96]):void 0;case S.array:return r.value===0?mi([128]):void 0;case S.map:return r.value===0?mi([160]):void 0;case S.uint:return r.value<24?mi([Number(r.value)]):void 0;case S.negint:if(r.value>=-24)return mi([31-Number(r.value)])}}var Zk={float64:!1,mapSorter:tN,quickEncodeToken:T7};function Jk(){let r=[];return r[S.uint.major]=Sn,r[S.negint.major]=Hh,r[S.bytes.major]=Aa,r[S.string.major]=t7,r[S.array.major]=Gh,r[S.map.major]=Wh,r[S.tag.major]=Yh,r[S.float.major]=Qh,r}var D7=Jk(),h2=new yu,Ta=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(`${Sa} object contains circular references`);return new Ta(t,e)}},xs={null:new U(S.null,null),undefined:new U(S.undefined,void 0),true:new U(S.true,!0),false:new U(S.false,!1),emptyArray:new U(S.array,0),emptyMap:new U(S.map,0)},_s={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(S.float,r):r>=0?new U(S.uint,r):new U(S.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(S.uint,r):new U(S.negint,r)},Uint8Array(r,e,t,n){return new U(S.bytes,r)},string(r,e,t,n){return new U(S.string,r)},boolean(r,e,t,n){return r?xs.true:xs.false},null(r,e,t,n){return xs.null},undefined(r,e,t,n){return xs.undefined},ArrayBuffer(r,e,t,n){return new U(S.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(S.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[xs.emptyArray,new U(S.break)]:xs.emptyArray;n=Ta.createCheck(n,r);let i=[],s=0;for(let o of r)i[s++]=jh(o,t,n);return t.addBreakTokens?[new U(S.array,r.length),i,new U(S.break)]:[new U(S.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",s=i?r.keys():Object.keys(r),o=i?r.size:s.length;if(!o)return t.addBreakTokens===!0?[xs.emptyMap,new U(S.break)]:xs.emptyMap;n=Ta.createCheck(n,r);let a=[],c=0;for(let u of s)a[c++]=[jh(u,t,n),jh(i?r.get(u):r[u],t,n)];return eN(a,t),t.addBreakTokens?[new U(S.map,o),a,new U(S.break)]:[new U(S.map,o),a]}};_s.Map=_s.Object;_s.Buffer=_s.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))_s[`${r}Array`]=_s.DataView;function jh(r,e={},t){let n=Ty(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||_s[n];if(typeof i=="function"){let o=i(r,n,e,t);if(o!=null)return o}let s=_s[n];if(!s)throw new Error(`${Sa} unsupported type: ${n}`);return s(r,n,e,t)}function eN(r,e){e.mapSorter&&r.sort(e.mapSorter)}function tN(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,s=D7[i].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function C7(r,e,t,n){if(Array.isArray(e))for(let i of e)C7(r,i,t,n);else t[e.type.major](r,e,n)}function P7(r,e,t){let n=jh(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let s=e[n.type.major];if(s.encodedSize){let o=s.encodedSize(n,t),a=new yu(o);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return gu(a.chunks[0])}}return h2.reset(),C7(h2,n,e,t),h2.toBytes(!0)}function Zh(r,e){return e=Object.assign({},Zk,e),P7(r,D7,e)}var rN={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},f2=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=Hn[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Y} 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}},vu=Symbol.for("DONE"),Jh=Symbol.for("BREAK");function nN(r,e,t){let n=[];for(let i=0;i<r.value;i++){let s=xu(e,t);if(s===Jh){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed array`)}if(s===vu)throw new Error(`${Y} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=s}return n}function iN(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},s=n?new Map:void 0;for(let o=0;o<r.value;o++){let a=xu(e,t);if(a===Jh){if(r.value===1/0)break;throw new Error(`${Y} got unexpected break to lengthed map`)}if(a===vu)throw new Error(`${Y} found map but not enough entries (got ${o} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Y} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in i))throw new Error(`${Y} found repeat map key "${a}"`);let c=xu(e,t);if(c===vu)throw new Error(`${Y} found map but not enough entries (got ${o} [no value], expected ${r.value})`);n?s.set(a,c):i[a]=c}return n?s:i}function xu(r,e){if(r.done())return vu;let t=r.next();if(t.type===S.break)return Jh;if(t.type.terminal)return t.value;if(t.type===S.array)return nN(t,r,e);if(t.type===S.map)return iN(t,r,e);if(t.type===S.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=xu(r,e);return e.tags[t.value](n)}throw new Error(`${Y} tag not supported (${t.value})`)}throw new Error("unsupported")}function Wi(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Y} data to decode must be a Uint8Array`);e=Object.assign({},rN,e);let t=e.tokenizer||new f2(r,e),n=xu(t,e);if(n===vu)throw new Error(`${Y} did not find any content to decode`);if(n===Jh)throw new Error(`${Y} got unexpected break`);if(!t.done())throw new Error(`${Y} too many terminals, data makes no sense`);return n}function Me(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var z7=F(L7(),1);var Su=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},p2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},O7=r=>globalThis.DOMException===void 0?new p2(r):new DOMException(r),B7=r=>{let e=r.reason===void 0?O7("This operation was aborted."):r.reason;return e instanceof Error?e:O7(e)};function m2(r,e,t,n){let i,s=new Promise((o,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){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(B7(c)),c.addEventListener("abort",()=>{a(B7(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Su(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{o(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function g2(r,e,t){let n=0,i=r.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;t(r[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Ao=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)},Yi,Au=class{constructor(){Yi.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Ao(this,Yi,"f")[this.size-1].priority>=t.priority){Ao(this,Yi,"f").push(n);return}let i=g2(Ao(this,Yi,"f"),n,(s,o)=>o.priority-s.priority);Ao(this,Yi,"f").splice(i,0,n)}dequeue(){let e=Ao(this,Yi,"f").shift();return e?.run}filter(e){return Ao(this,Yi,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Ao(this,Yi,"f").length}};Yi=new WeakMap;var Rt=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},Q=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)},Mt,Iu,Tu,As,af,Du,tf,$n,Ru,nn,rf,sn,Cu,Ss,nf,M7,U7,q7,F7,K7,sf,y2,w2,cf,V7,of,uf=class extends Error{},vt=class extends z7.default{constructor(e){var t,n,i,s;if(super(),Mt.add(this),Iu.set(this,void 0),Tu.set(this,void 0),As.set(this,0),af.set(this,void 0),Du.set(this,void 0),tf.set(this,0),$n.set(this,void 0),Ru.set(this,void 0),nn.set(this,void 0),rf.set(this,void 0),sn.set(this,0),Cu.set(this,void 0),Ss.set(this,void 0),nf.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:Au,...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 \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);Rt(this,Iu,e.carryoverConcurrencyCount,"f"),Rt(this,Tu,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Rt(this,af,e.intervalCap,"f"),Rt(this,Du,e.interval,"f"),Rt(this,nn,new e.queueClass,"f"),Rt(this,rf,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Rt(this,nf,e.throwOnTimeout===!0,"f"),Rt(this,Ss,e.autoStart===!1,"f")}get concurrency(){return Q(this,Cu,"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})`);Rt(this,Cu,e,"f"),Q(this,Mt,"m",cf).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Q(this,nf,"f"),...t},new Promise((n,i)=>{Q(this,nn,"f").enqueue(async()=>{var s,o,a;Rt(this,sn,(o=Q(this,sn,"f"),o++,o),"f"),Rt(this,As,(a=Q(this,As,"f"),a++,a),"f");try{if(!((s=t.signal)===null||s===void 0)&&s.aborted)throw new uf("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=m2(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Q(this,Mt,"m",V7).call(this,t.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Su&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Q(this,Mt,"m",q7).call(this)}},t),this.emit("add"),Q(this,Mt,"m",sf).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Q(this,Ss,"f")?(Rt(this,Ss,!1,"f"),Q(this,Mt,"m",cf).call(this),this):this}pause(){Rt(this,Ss,!0,"f")}clear(){Rt(this,nn,new(Q(this,rf,"f")),"f")}async onEmpty(){Q(this,nn,"f").size!==0&&await Q(this,Mt,"m",of).call(this,"empty")}async onSizeLessThan(e){Q(this,nn,"f").size<e||await Q(this,Mt,"m",of).call(this,"next",()=>Q(this,nn,"f").size<e)}async onIdle(){Q(this,sn,"f")===0&&Q(this,nn,"f").size===0||await Q(this,Mt,"m",of).call(this,"idle")}get size(){return Q(this,nn,"f").size}sizeBy(e){return Q(this,nn,"f").filter(e).length}get pending(){return Q(this,sn,"f")}get isPaused(){return Q(this,Ss,"f")}};Iu=new WeakMap,Tu=new WeakMap,As=new WeakMap,af=new WeakMap,Du=new WeakMap,tf=new WeakMap,$n=new WeakMap,Ru=new WeakMap,nn=new WeakMap,rf=new WeakMap,sn=new WeakMap,Cu=new WeakMap,Ss=new WeakMap,nf=new WeakMap,Mt=new WeakSet,M7=function(){return Q(this,Tu,"f")||Q(this,As,"f")<Q(this,af,"f")},U7=function(){return Q(this,sn,"f")<Q(this,Cu,"f")},q7=function(){var e;Rt(this,sn,(e=Q(this,sn,"f"),e--,e),"f"),Q(this,Mt,"m",sf).call(this),this.emit("next")},F7=function(){Q(this,Mt,"m",w2).call(this),Q(this,Mt,"m",y2).call(this),Rt(this,Ru,void 0,"f")},K7=function(){let e=Date.now();if(Q(this,$n,"f")===void 0){let t=Q(this,tf,"f")-e;if(t<0)Rt(this,As,Q(this,Iu,"f")?Q(this,sn,"f"):0,"f");else return Q(this,Ru,"f")===void 0&&Rt(this,Ru,setTimeout(()=>{Q(this,Mt,"m",F7).call(this)},t),"f"),!0}return!1},sf=function(){if(Q(this,nn,"f").size===0)return Q(this,$n,"f")&&clearInterval(Q(this,$n,"f")),Rt(this,$n,void 0,"f"),this.emit("empty"),Q(this,sn,"f")===0&&this.emit("idle"),!1;if(!Q(this,Ss,"f")){let e=!Q(this,Mt,"a",K7);if(Q(this,Mt,"a",M7)&&Q(this,Mt,"a",U7)){let t=Q(this,nn,"f").dequeue();return t?(this.emit("active"),t(),e&&Q(this,Mt,"m",y2).call(this),!0):!1}}return!1},y2=function(){Q(this,Tu,"f")||Q(this,$n,"f")!==void 0||(Rt(this,$n,setInterval(()=>{Q(this,Mt,"m",w2).call(this)},Q(this,Du,"f")),"f"),Rt(this,tf,Date.now()+Q(this,Du,"f"),"f"))},w2=function(){Q(this,As,"f")===0&&Q(this,sn,"f")===0&&Q(this,$n,"f")&&(clearInterval(Q(this,$n,"f")),Rt(this,$n,void 0,"f")),Rt(this,As,Q(this,Iu,"f")?Q(this,sn,"f"):0,"f"),Q(this,Mt,"m",cf).call(this)},cf=function(){for(;Q(this,Mt,"m",sf).call(this););},V7=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new uf("The task was aborted."))},{once:!0})})},of=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};var aN=new TextDecoder;function b2(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)<<n:(i&127)*2**n,i<128)break}return[t,e]}function lf(r,e){let t;[t,e]=b2(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function H7(r,e){let t;return[t,e]=b2(r,e),[t&7,t>>3,e]}function cN(r){let e={},t=r.length,n=0;for(;n<t;){let i,s;if([i,s,n]=H7(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=lf(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let o;[o,n]=lf(r,n),e.Name=aN.decode(o)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=b2(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function $7(r){let e=r.length,t=0,n,i=!1,s;for(;t<e;){let a,c;if([a,c,t]=H7(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=lf(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=lf(r,t),n.push(cN(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return s&&(o.Data=s),o.Links=n||[],o}var ZZ=new TextEncoder,JZ=2**32,eJ=2**31;var nJ=new TextEncoder;var G7=112;function W7(r){let e=$7(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let i={};try{i.Hash=ee.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 Y7=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===S.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===S.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[S.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);e.push(i)}[S.negint.major](e,t){this[S.uint.major](e,t)}[S.bytes.major](e,t){throw new Error(`${Sa} unsupported type: Uint8Array`)}[S.string.major](e,t){this.prefix(e);let n=zh(JSON.stringify(t.value));e.push(n.length>32?gu(n):n)}[S.array.major](e,t){this.prefix(e),this.inRecursive.push({type:S.array,elements:0}),e.push([91])}[S.map.major](e,t){this.prefix(e),this.inRecursive.push({type:S.map,elements:0}),e.push([123])}[S.tag.major](e,t){}[S.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(o.type===S.array)e.push([93]);else if(o.type===S.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(`${Sa} 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=[],s=!1;for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o),!s&&(i[o]===46||i[o]===101||i[o]===69)&&(s=!0);s||(i.push(46),i.push(48)),e.push(i)}};var Da=class{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}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<e.length)throw new Error(`${Y} unexpected end of input at position ${this.pos}`);for(let t=0;t<e.length;t++)if(this.data[this.pos++]!==e[t])throw new Error(`${Y} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,t=!1,n=!1,i=a=>{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 U(S.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(`${Y} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Y} 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 s=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),o=parseFloat(s);return n?new U(S.float,o,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new U(o>=0?S.uint:S.negint,o,this.pos-e):new U(o>=0?S.uint:S.negint,BigInt(s),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Y} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let s=this.pos,o=0;s<this.data.length&&o<65536;s++,o++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,s));return this.pos=s+1,new U(S.string,c,o)}}let e=this.pos,t=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${Y} unexpected end of unicode escape sequence at position ${this.pos}`);let s=0;for(let o=0;o<4;o++){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(`${Y} unexpected unicode escape character at position ${this.pos}`);s=s*16+a,this.pos++}return s},i=()=>{let s=this.ch(),o=null,a=s>239?4:s>223?3:s>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${Y} unexpected unicode sequence at position ${this.pos}`);let c,u,l,h;switch(a){case 1:s<128&&(o=s);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(h=(s&31)<<6|c&63,h>127&&(o=h));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(h=(s&15)<<12|(c&63)<<6|u&63,h>2047&&(h<55296||h>57343)&&(o=h));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&&(h=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,h>65535&&h<1114112&&(o=h))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this.pos+=a};for(;!this.done();){let s=this.ch(),o;switch(s){case 92:if(this.pos++,this.done())throw new Error(`${Y} unexpected string termination at position ${this.pos}`);switch(o=this.ch(),this.pos++,o){case 34:case 39:case 92:case 47:t.push(o);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(`${Y} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new U(S.string,o2(t),this.pos-e);default:if(s<32)throw new Error(`${Y} invalid control character at position ${this.pos}`);s<128?(t.push(s),this.pos++):i()}}throw new Error(`${Y} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new U(S.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new U(S.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(S.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(S.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(S.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(`${Y} 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 U(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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 U(S.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 U(S.break,void 0,1);if(this.ch()!==44)throw new Error(`${Y} 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 U(S.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Y} 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(`${Y} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function E2(r,e){return e=Object.assign({tokenizer:new Da(r,e)},e),Wi(r,e)}var Q7={codec:G7,async*walk(r){yield*W7(r).Links.map(t=>t.Hash)}},X7={codec:ch,async*walk(){}},j7=42,Z7={codec:113,async*walk(r){let e=[],t=[];t[j7]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let i=ee.decode(n.subarray(1));return e.push(i),i},Wi(r,{tags:t}),yield*e}},v2=class extends Da{tokenBuffer;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===S.map){let t=this._next();if(t.type===S.string&&t.value==="/"){let n=this._next();if(n.type===S.string){if(this._next().type!==S.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(S.tag,42,0)}if(n.type===S.map){let i=this._next();if(i.type===S.string&&i.value==="bytes"){let s=this._next();if(s.type===S.string){for(let a=0;a<2;a++)if(this._next().type!==S.break)throw new Error("Invalid encoded Bytes form");let o=Ki.decode(`m${s.value}`);return new U(S.bytes,o,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},J7={codec:297,async*walk(r){let e=[],t=[];t[j7]=n=>{let i=ee.parse(n);return e.push(i),i},E2(r,{tags:t,tokenizer:new v2(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}};var hN=[X7,Q7,Z7,J7],n9="/pin/",e9="/pinned-block/",x2=au,t9=1;function r9(r){return r.version===0&&(r=r.toV1()),new ve(`${n9}${r.toString(x2)}`)}var hf=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers={},[...hN,...n].forEach(i=>{this.dagWalkers[i.codec]=i})}async add(e,t={}){let n=r9(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let s=new vt({concurrency:t9});s.add(async()=>{await this.#e(e,s,c=>{c.pinnedBy.find(u=>pe(u,e.bytes))==null&&(c.pinCount++,c.pinnedBy.push(e.bytes))},{...t,depth:i})});let o=Me();s.on("error",c=>{s.clear(),o.reject(c)}),await Promise.race([s.onIdle(),o.promise]);let a={depth:i,metadata:t.metadata??{}};return await this.datastore.put(n,Zh(a),t),{cid:e,...a}}async#e(e,t,n,i){if(i.depth===-1)return;let s=this.dagWalkers[e.code];if(s==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let o=await this.blockstore.get(e);await this.#t(e,n,i);for await(let a of s.walk(o))t.add(async()=>{await this.#e(a,t,n,{...i,depth:i.depth-1})})}async#t(e,t,n){let i=new ve(`${e9}${x2.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=Wi(await this.datastore.get(i,n))}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(t(s),s.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,Zh(s),n)}async rm(e,t={}){let n=r9(e),i=await this.datastore.get(n,t),s=Wi(i);await this.datastore.delete(n,t);let o=new vt({concurrency:t9});return o.add(async()=>{await this.#e(e,o,a=>{a.pinCount--,a.pinnedBy=a.pinnedBy.filter(c=>pe(c,e.bytes))},{...t,depth:s.depth})}),await o.onIdle(),{cid:e,...s}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:n9+(e.cid!=null?`${e.cid.toString(au)}`:"")},e)){let i=ee.parse(t.toString().substring(5),au),s=Wi(n);yield{cid:i,...s}}}async isPinned(e,t={}){let n=new ve(`${e9}${x2.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var _2=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},S2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},i9=r=>globalThis.DOMException===void 0?new S2(r):new DOMException(r),s9=r=>{let e=r.reason===void 0?i9("This operation was aborted."):r.reason;return e instanceof Error?e:i9(e)};function A2(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,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:h}=e;h.aborted&&u(s9(h)),h.addEventListener("abort",()=>{u(s9(h))})}let l=new _2;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}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(h){u(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var o9=(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 R2="lock:worker:request-read",I2="lock:worker:release-read",T2="lock:master:grant-read",D2="lock:worker:request-write",C2="lock:worker:release-write",P2="lock:master:grant-write";var Rs={},Ca=r=>{r.addEventListener("message",e=>{Ca.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ca.dispatchEvent("message",r,e)})};Ca.addEventListener=(r,e)=>{Rs[r]==null&&(Rs[r]=[]),Rs[r].push(e)};Ca.removeEventListener=(r,e)=>{Rs[r]!=null&&(Rs[r]=Rs[r].filter(t=>t===e))};Ca.dispatchEvent=function(r,e,t){Rs[r]!=null&&Rs[r].forEach(n=>n(e,t))};var k2=Ca;var a9=(r,e,t,n,i)=>(s,o)=>{if(o.data.type!==t)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let h={type:l.data.type,name:l.data.name,identifier:l.data.identifier};h.type===n&&h.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},c9=(r,e,t,n)=>async()=>{let i=o9();return globalThis.postMessage({type:e,identifier:i,name:r}),await new Promise(s=>{let o=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",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:r})}))};globalThis.addEventListener("message",o)})},fN={singleProcess:!1},u9=r=>{if(r=Object.assign({},fN,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return k2.addEventListener("message",a9(t,"requestReadLock",R2,I2,T2)),k2.addEventListener("message",a9(t,"requestWriteLock",D2,C2,P2)),t}return{isWorker:!0,readLock:t=>c9(t,R2,T2,I2),writeLock:t=>c9(t,D2,P2,C2)}};var Ro={},Is;async function N2(r,e){let t,n=new Promise(i=>{t=i});return r.add(async()=>await A2((async()=>await new Promise(i=>{t(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var dN=(r,e)=>{if(Is.isWorker===!0)return{readLock:Is.readLock(r,e),writeLock:Is.writeLock(r,e)};let t=new vt({concurrency:1}),n;return{async readLock(){if(n!=null)return await N2(n,e);n=new vt({concurrency:e.concurrency,autoStart:!1});let i=n,s=N2(n,e);return t.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await N2(t,e)}}},pN={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Pu(r){let e=Object.assign({},pN,r);return Is==null&&(Is=u9(e),Is.isWorker!==!0&&(Is.addEventListener("requestReadLock",t=>{Ro[t.data.name]!=null&&Ro[t.data.name].readLock().then(async n=>await t.data.handler().finally(()=>n()))}),Is.addEventListener("requestWriteLock",async t=>{Ro[t.data.name]!=null&&Ro[t.data.name].writeLock().then(async n=>await t.data.handler().finally(()=>n()))}))),Ro[e.name]==null&&(Ro[e.name]=dN(e.name,e)),Ro[e.name]}var ff=class{lock;child;bitswap;pins;constructor(e,t,n={}){this.child=e,this.bitswap=n.bitswap,this.pins=t,this.lock=Pu({singleProcess:n.holdGcLock})}unwrap(){return this.child}async put(e,t,n={}){let i=await this.lock.readLock();try{return await this.child.has(e)?(n.onProgress?.(new Ze("blocks:put:duplicate",e)),e):(this.bitswap?.isStarted()===!0&&(n.onProgress?.(new Ze("blocks:put:bitswap:notify",e)),this.bitswap.notify(e,t,n)),n.onProgress?.(new Ze("blocks:put:blockstore:put",e)),await this.child.put(e,t,n))}finally{i()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{let i=Fr(e,async({cid:o})=>{let a=await this.child.has(o);return a&&t.onProgress?.(new Ze("blocks:put-many:duplicate",o)),!a}),s=cu(i,({cid:o,block:a})=>{t.onProgress?.(new Ze("blocks:put-many:bitswap:notify",o)),this.bitswap?.notify(o,a,t)});t.onProgress?.(new Ze("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(s,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{if(this.bitswap?.isStarted()!=null&&!await this.child.has(e)){t.onProgress?.(new Ze("blocks:get:bitswap:get",e));let i=await this.bitswap.want(e,t);return t.onProgress?.(new Ze("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),i}return t.onProgress?.(new Ze("blocks:get:blockstore:get",e)),await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{t.onProgress?.(new Ze("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(cu(e,async i=>{if(this.bitswap?.isStarted()===!0&&!await this.child.has(i)){t.onProgress?.(new Ze("blocks:get-many:bitswap:get",i));let s=await this.bitswap.want(i,t);t.onProgress?.(new Ze("blocks:get-many:blockstore:put",i)),await this.child.put(i,s,t)}}))}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");t.onProgress?.(new Ze("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let i=this;t.onProgress?.(new Ze("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let s of e){if(await i.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{e.onProgress?.(new Ze("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}finally{t()}}};var L2=new ve("/version"),l9=1;async function h9(r){if(!await r.has(L2)){await r.put(L2,q(`${l9}`));return}let e=await r.get(L2),t=B(e);if(parseInt(t,10)!==l9)throw new Error("Unknown datastore version, a datastore migration may be required")}var O2=D("helia"),df=class{libp2p;blockstore;datastore;pins;#e;constructor(e){let t=[Pe,mp,li,...e.hashers??[]];this.#e=Iy(e.libp2p,e.blockstore,{hashLoader:{getHasher:async n=>{let i=t.find(s=>s.code===n||s.name===n);if(i!=null)return i;throw new Error(`Could not load hasher for code/name "${n}"`)}}}),this.pins=new hf(e.datastore,e.blockstore,e.dagWalkers??[]),this.libp2p=e.libp2p,this.blockstore=new ff(e.blockstore,this.pins,{bitswap:this.#e,holdGcLock:e.holdGcLock}),this.datastore=e.datastore}async start(){await h9(this.datastore),await this.#e?.start(),await this.libp2p.start()}async stop(){await this.libp2p.stop(),await this.#e?.stop()}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();O2("gc start"),await Yr(i.deleteMany(async function*(){for await(let{cid:s}of i.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new Ze("helia:gc:deleted",s))}catch(o){O2.error("Error during gc",o),e.onProgress?.(new Ze("helia:gc:error",o))}}()))}finally{t()}O2("gc finished")}};var B2=Symbol.for("@libp2p/peer-id");function pf(r){return r!=null&&!!r[B2]}var mN=Symbol.for("nodejs.util.inspect.custom"),f9=Object.values(En).map(r=>r.decoder).reduce((r,e)=>r.or(e),En.identity.decoder),d9=114,M2=36,U2=37,ku=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[B2](){return!0}toString(){return this.string==null&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return ee.createV1(d9,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return pe(this.multihash.bytes,e);if(typeof e=="string")return oe(e).equals(this);if(e?.multihash?.bytes!=null)return pe(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[mN](){return`PeerId(${this.toString()})`}},Pa=class extends ku{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},ka=class extends ku{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Na=class extends ku{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function oe(r,e){if(e=e??f9,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=ui(me.decode(`z${r}`));return r.startsWith("12D")?new ka({multihash:t}):r.startsWith("16U")?new Na({multihash:t}):new Pa({multihash:t})}return It(f9.decode(r))}function It(r){try{let e=ui(r);if(e.code===li.code){if(e.digest.length===M2)return new ka({multihash:e});if(e.digest.length===U2)return new Na({multihash:e})}if(e.code===Pe.code)return new Pa({multihash:e})}catch{return gN(ee.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function gN(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==d9)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Pe.code)return new Pa({multihash:r.multihash});if(e.code===li.code){if(e.digest.length===M2)return new ka({multihash:r.multihash});if(e.digest.length===U2)return new Na({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function er(r,e){return r.length===M2?new ka({multihash:Un(li.code,r),privateKey:e}):r.length===U2?new Na({multihash:Un(li.code,r),privateKey:e}):new Pa({multihash:await Pe.digest(r),publicKey:r,privateKey:e})}var Ue=class extends EventTarget{#e=new Map;listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t){return this.dispatchEvent(new Je(e,t))}},F2=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Je=globalThis.CustomEvent??F2;var mf=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<t;i++)this.history[i]=[]}get size(){return this.msgs.size}put(e,t,n=!1){let{msgIdStr:i}=e;return this.msgs.has(i)?!1:(this.msgs.set(i,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){let n=this.msgs.get(e);n&&!n.validated&&n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let n=this.msgs.get(e);if(!n)return null;let i=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,i),{msg:n.message,count:i}}getGossipIDs(e){let t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach(i=>{let s=this.msgs.get(i.msgIdStr);if(s&&s.validated&&e.has(i.topic)){let o=t.get(i.topic);o||(o=[],t.set(i.topic,o)),o.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 G9=F($9(),1),{RPC:Mu}=G9.default;var J2="/floodsub/1.0.0",e3="/meshsub/1.0.0",t3="/meshsub/1.1.0";var W9="ERR_TOPIC_VALIDATOR_REJECT",Y9="ERR_TOPIC_VALIDATOR_IGNORE";function wi(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let n=e(),i=r[t];r[t]=r[n],r[n]=i}return r}function Q9(r){return B(r,"base64")}var jf={};Ae(jf,{generateEphemeralKeyPair:()=>Pb,generateKeyPair:()=>il,generateKeyPairFromSeed:()=>ZB,importKey:()=>Xa,keyStretcher:()=>Mb,keysPBM:()=>Ka,marshalPrivateKey:()=>Z3,marshalPublicKey:()=>Qa,supportedKeys:()=>Ii,unmarshalPrivateKey:()=>cn,unmarshalPublicKey:()=>kr});var Cre=F(qu(),1),Pre=F(lb(),1);var Xf=F(rt(),1);var O3={};Ae(O3,{Ed25519PrivateKey:()=>Oo,Ed25519PublicKey:()=>Yu,generateKeyPair:()=>gB,generateKeyPairFromSeed:()=>L3,unmarshalEd25519PrivateKey:()=>pB,unmarshalEd25519PublicKey:()=>mB});var XO=F(Ns(),1);var sr=BigInt(0),Ne=BigInt(1),Us=BigInt(2),jO=BigInt(8),hb=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),pt=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:hb,n:hb,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var gb=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),Hu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),pte=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),ZO=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),JO=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),tB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ie=class{constructor(e,t,n,i){this.x=e,this.y=t,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof _t))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(_t.ZERO)?Ie.ZERO:new Ie(e.x,e.y,Ne,L(e.x*e.y))}static toAffineBatch(e){let t=iB(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){db(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=L(t*a),u=L(s*i),l=L(n*a),h=L(o*i);return c===u&&l===h}negate(){return new Ie(L(-this.x),this.y,this.z,L(-this.t))}double(){let{x:e,y:t,z:n}=this,{a:i}=pt,s=L(e*e),o=L(t*t),a=L(Us*L(n*n)),c=L(i*s),u=e+t,l=L(L(u*u)-s-o),h=c+o,f=h-a,d=c-o,p=L(l*f),m=L(h*d),g=L(l*d),y=L(f*h);return new Ie(p,m,y,g)}add(e){db(e);let{x:t,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=L((n-t)*(a+o)),h=L((n+t)*(a-o)),f=L(h-l);if(f===sr)return this.double();let d=L(i*Us*u),p=L(s*Us*c),m=p+d,g=h+l,y=p-d,b=L(m*f),E=L(g*y),R=L(m*y),v=L(f*g);return new Ie(b,E,v,R)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let t=1+256/e,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(Ie.BASE)&&(t=_t.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&T3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=Ie.normalizeZ(i),T3.set(t,i)));let s=Ie.ZERO,o=Ie.BASE,a=1+256/n,c=2**(n-1),u=BigInt(2**n-1),l=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&u);e>>=h,p>c&&(p-=l,e+=Ne);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add(fb(y,i[m])):s=s.add(fb(b,i[g]))}return Ie.normalizeZ([s,o])[0]}multiply(e,t){return this.wNAF(Mf(e,pt.l),t)}multiplyUnsafe(e){let t=Mf(e,pt.l,!1),n=Ie.BASE,i=Ie.ZERO;if(t===sr)return i;if(this.equals(i)||t===Ne)return this;if(this.equals(n))return this.wNAF(t);let s=i,o=this;for(;t>sr;)t&Ne&&(s=s.add(o)),o=o.double(),t>>=Ne;return s}isSmallOrder(){return this.multiplyUnsafe(pt.h).equals(Ie.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(pt.l/Us).double();return pt.l%Us&&(e=e.add(this)),e.equals(Ie.ZERO)}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(Ie.ZERO);e==null&&(e=s?jO:Uf(i));let o=L(t*e),a=L(n*e),c=L(i*e);if(s)return _t.ZERO;if(c!==Ne)throw new Error("invZ was invalid");return new _t(o,a)}fromRistrettoBytes(){A3()}toRistrettoBytes(){A3()}fromRistrettoHash(){A3()}};Ie.BASE=new Ie(pt.Gx,pt.Gy,Ne,L(pt.Gx*pt.Gy));Ie.ZERO=new Ie(sr,Ne,Ne,sr);function fb(r,e){let t=e.negate();return r?t:e}function db(r){if(!(r instanceof Ie))throw new TypeError("ExtendedPoint expected")}function S3(r){if(!(r instanceof zr))throw new TypeError("RistrettoPoint expected")}function A3(){throw new Error("Legacy method: switch to RistrettoPoint")}var zr=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:t}=pt,n=L(Hu*e*e),i=L((n+Ne)*eB),s=BigInt(-1),o=L((s-t*n)*L(n+t)),{isValid:a,value:c}=C3(i,o),u=L(c*e);Ms(u)||(u=L(-u)),a||(c=u),a||(s=n);let l=L(s*(n-Ne)*tB-o),h=c*c,f=L((c+c)*o),d=L(l*ZO),p=L(Ne-h),m=L(Ne+h);return new Ie(L(f*m),L(p*d),L(d*m),L(f*p))}static hashToCurve(e){e=Fs(e,64);let t=R3(e.slice(0,32)),n=this.calcElligatorRistrettoMap(t),i=R3(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new zr(n.add(s))}static fromHex(e){e=Fs(e,32);let{a:t,d:n}=pt,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=R3(e);if(!oB($u(s),e)||Ms(s))throw new Error(i);let o=L(s*s),a=L(Ne+t*o),c=L(Ne-t*o),u=L(a*a),l=L(c*c),h=L(t*n*u-l),{isValid:f,value:d}=mb(L(h*l)),p=L(d*c),m=L(d*p*h),g=L((s+s)*p);Ms(g)&&(g=L(-g));let y=L(a*m),b=L(g*y);if(!f||Ms(b)||y===sr)throw new Error(i);return new zr(new Ie(g,y,Ne,b))}toRawBytes(){let{x:e,y:t,z:n,t:i}=this.ep,s=L(L(n+t)*L(n-t)),o=L(e*t),a=L(o*o),{value:c}=mb(L(s*a)),u=L(c*s),l=L(c*o),h=L(u*l*i),f;if(Ms(i*h)){let p=L(t*Hu),m=L(e*Hu);e=p,t=m,f=L(u*JO)}else f=l;Ms(e*h)&&(t=L(-t));let d=L((n-t)*f);return Ms(d)&&(d=L(-d)),$u(d)}toHex(){return Gu(this.toRawBytes())}toString(){return this.toHex()}equals(e){S3(e);let t=this.ep,n=e.ep,i=L(t.x*n.y)===L(t.y*n.x),s=L(t.y*n.y)===L(t.x*n.x);return i||s}add(e){return S3(e),new zr(this.ep.add(e.ep))}subtract(e){return S3(e),new zr(this.ep.subtract(e.ep))}multiply(e){return new zr(this.ep.multiply(e))}multiplyUnsafe(e){return new zr(this.ep.multiplyUnsafe(e))}};zr.BASE=new zr(Ie.BASE);zr.ZERO=new zr(Ie.ZERO);var T3=new WeakMap,_t=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,T3.delete(this)}static fromHex(e,t=!0){let{d:n,P:i}=pt;e=Fs(e,32);let s=e.slice();s[31]=e[31]&-129;let o=Wu(s);if(t&&o>=i)throw new Error("Expected 0 < hex < P");if(!t&&o>=gb)throw new Error("Expected 0 < hex < 2**256");let a=L(o*o),c=L(a-Ne),u=L(n*a+Ne),{isValid:l,value:h}=C3(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let f=(h&Ne)===Ne;return(e[31]&128)!==0!==f&&(h=L(-h)),new _t(h,o)}static async fromPrivateKey(e){return(await Ff(e)).point}toRawBytes(){let e=$u(this.y);return e[31]|=this.x&Ne?128:0,e}toHex(){return Gu(this.toRawBytes())}toX25519(){let{y:e}=this,t=L((Ne+e)*Uf(Ne-e));return $u(t)}isTorsionFree(){return Ie.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new _t(L(-this.x),this.y)}add(e){return Ie.fromAffine(this).add(Ie.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ie.fromAffine(this).multiply(e,this).toAffine()}};_t.BASE=new _t(pt.Gx,pt.Gy);_t.ZERO=new _t(sr,Ne);var Lo=class{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){let t=Fs(e,64),n=_t.fromHex(t.slice(0,32),!1),i=Wu(t.slice(32,64));return new Lo(n,i)}assertValidity(){let{r:e,s:t}=this;if(!(e instanceof _t))throw new Error("Expected Point instance");return Mf(t,pt.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set($u(this.s),32),e}toHex(){return Gu(this.toRawBytes())}};function pb(...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;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var rB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Gu(r){if(!(r instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=rB[r[t]];return e}function D3(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function yb(r){let t=r.toString(16).padStart(64,"0");return D3(t)}function $u(r){return yb(r).reverse()}function Ms(r){return(L(r)&Ne)===Ne}function Wu(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+Gu(Uint8Array.from(r).reverse()))}var nB=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function R3(r){return L(Wu(r)&nB)}function L(r,e=pt.P){let t=r%e;return t>=sr?t:e+t}function Uf(r,e=pt.P){if(r===sr||e<=sr)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=L(r,e),n=e,i=sr,s=Ne,o=Ne,a=sr;for(;t!==sr;){let u=n/t,l=n%t,h=i-o*u,f=s-a*u;n=t,t=l,i=o,s=a,o=h,a=f}if(n!==Ne)throw new Error("invert: does not exist");return L(i,e)}function iB(r,e=pt.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===sr?s:(t[a]=s,L(s*o,e)),Ne),i=Uf(n,e);return r.reduceRight((s,o,a)=>o===sr?s:(t[a]=L(s*t[a],e),L(s*o,e)),i),t}function Ai(r,e){let{P:t}=pt,n=r;for(;e-- >sr;)n*=n,n%=t;return n}function sB(r){let{P:e}=pt,t=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=r*r%e*r%e,u=Ai(c,Us)*c%e,l=Ai(u,Ne)*r%e,h=Ai(l,t)*l%e,f=Ai(h,n)*h%e,d=Ai(f,i)*f%e,p=Ai(d,s)*d%e,m=Ai(p,o)*p%e,g=Ai(m,o)*p%e,y=Ai(g,n)*h%e;return{pow_p_5_8:Ai(y,Us)*r%e,b2:c}}function C3(r,e){let t=L(e*e*e),n=L(t*t*e),i=sB(r*n).pow_p_5_8,s=L(r*t*i),o=L(e*s*s),a=s,c=L(s*Hu),u=o===r,l=o===L(-r),h=o===L(-r*Hu);return u&&(s=a),(l||h)&&(s=c),Ms(s)&&(s=L(-s)),{isValid:u||l,value:s}}function mb(r){return C3(Ne,r)}function Bf(r){return L(Wu(r),pt.l)}function oB(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Fs(r,e){let t=r instanceof Uint8Array?Uint8Array.from(r):D3(r);if(typeof e=="number"&&t.length!==e)throw new Error(`Expected ${e} bytes`);return t}function Mf(r,e,t=!0){if(!e)throw new TypeError("Specify max value");if(typeof r=="number"&&Number.isSafeInteger(r)&&(r=BigInt(r)),typeof r=="bigint"&&r<e){if(t){if(sr<r)return r}else if(sr<=r)return r}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function aB(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function cB(r){if(r=typeof r=="bigint"||typeof r=="number"?yb(Mf(r,gb)):Fs(r),r.length!==32)throw new Error("Expected 32 bytes");return r}function uB(r){let e=aB(r.slice(0,32)),t=r.slice(32,64),n=Bf(e),i=_t.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:t,scalar:n,point:i,pointBytes:s}}var I3;async function Ff(r){return uB(await Ks.sha512(cB(r)))}async function P3(r){return(await Ff(r)).pointBytes}async function wb(r,e){r=Fs(r);let{prefix:t,scalar:n,pointBytes:i}=await Ff(e),s=Bf(await Ks.sha512(t,r)),o=_t.BASE.multiply(s),a=Bf(await Ks.sha512(o.toRawBytes(),i,r)),c=L(s+a*n,pt.l);return new Lo(o,c).toRawBytes()}function lB(r,e,t){e=Fs(e),t instanceof _t||(t=_t.fromHex(t,!1));let{r:n,s:i}=r instanceof Lo?r.assertValidity():Lo.fromHex(r),s=Ie.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:t,msg:e}}function hB(r,e,t,n){let i=Bf(n),s=Ie.fromAffine(r).multiplyUnsafe(i);return Ie.fromAffine(e).add(s).subtract(t).multiplyUnsafe(pt.h).equals(Ie.ZERO)}async function bb(r,e,t){let{r:n,SB:i,msg:s,pub:o}=lB(r,e,t),a=await Ks.sha512(n.toRawBytes(),o.toRawBytes(),s);return hB(o,n,i,a)}_t.BASE._setWindowSize(8);var Bs={node:XO,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Ks={bytesToHex:Gu,hexToBytes:D3,concatBytes:pb,getExtendedPublicKey:Ff,mod:L,invert:Uf,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:r=>{if(r=Fs(r),r.length<40||r.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return L(Wu(r),pt.l-Ne)+Ne},randomBytes:(r=32)=>{if(Bs.web)return Bs.web.getRandomValues(new Uint8Array(r));if(Bs.node){let{randomBytes:e}=Bs.node;return new Uint8Array(e(r).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ks.randomBytes(32),sha512:async(...r)=>{let e=pb(...r);if(Bs.web){let t=await Bs.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(t)}else{if(Bs.node)return Uint8Array.from(Bs.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(r=8,e=_t.BASE){let t=e.equals(_t.BASE)?e:new _t(e.x,e.y);return t._setWindowSize(r),t.multiply(Us),t},sha512Sync:void 0};Object.defineProperties(Ks,{sha512Sync:{configurable:!1,get(){return I3},set(r){I3||(I3=r)}}});var Ua=32,Zi=64,Kf=32;async function Eb(){let r=Ks.randomPrivateKey(),e=await P3(r);return{privateKey:Sb(r,e),publicKey:e}}async function vb(r){if(r.length!==Kf)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 P3(e);return{privateKey:Sb(e,t),publicKey:t}}async function xb(r,e){let t=r.subarray(0,Kf);return wb(e,t)}async function _b(r,e,t){return bb(e,t,r)}function Sb(r,e){let t=new Uint8Array(Zi);for(let n=0;n<Kf;n++)t[n]=r[n],t[Kf+n]=e[n];return t}var Kt={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 k3={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function qf(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,i=r?.digest??"SHA-256",s=r?.saltLength??16,o=r?.iterations??32767,a=Kt.get();t*=8;async function c(h,f){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof f=="string"&&(f=q(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",k3,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",k3,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,h);return he([d,m.iv,new Uint8Array(y)])}async function u(h,f){let d=h.subarray(0,s),p=h.subarray(s,s+n),m=h.subarray(s+n),g={name:e,iv:p};typeof f=="string"&&(f=q(f));let y;if(f.length===0)try{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},R=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,R,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",k3,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},R=await a.subtle.importKey("raw",f,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,R,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function Fa(r,e){let n=await qf().encrypt(r,e);return Ki.encode(n)}var Ka={};Ae(Ka,{KeyType:()=>mt,PrivateKey:()=>Xn,PublicKey:()=>Qn});var mt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(mt||(mt={}));var N3;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(N3||(N3={}));(function(r){r.codec=()=>Ht(N3)})(mt||(mt={}));var Qn;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),mt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=mt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Qn||(Qn={}));var Xn;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),mt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.Type=mt.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Xn||(Xn={}));var Yu=class{_key;constructor(e){this._key=qa(e,Ua)}async verify(e,t){return _b(this._key,t,e)}marshal(){return this._key}get bytes(){return Qn.encode({Type:mt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}},Oo=class{_key;_publicKey;constructor(e,t){this._key=qa(e,Zi),this._publicKey=qa(t,Ua)}async sign(e){return xb(this._key,e)}get public(){return new Yu(this._publicKey)}marshal(){return this._key}get bytes(){return Xn.encode({Type:mt.Ed25519,Data:this.marshal()}).subarray()}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}async id(){let e=li.digest(this.public.bytes);return me.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Fa(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function pB(r){if(r.length>Zi){r=qa(r,Zi+Ua);let n=r.subarray(0,Zi),i=r.subarray(Zi,r.length);return new Oo(n,i)}r=qa(r,Zi);let e=r.subarray(0,Zi),t=r.subarray(Ua);return new Oo(e,t)}function mB(r){return r=qa(r,Ua),new Yu(r)}async function gB(){let{privateKey:r,publicKey:e}=await Eb();return new Oo(r,e)}async function L3(r){let{privateKey:e,publicKey:t}=await vb(r);return new Oo(e,t)}function qa(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new w(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var Tte=F(Ft(),1),Dte=F(kf(),1),Rb=F(rt(),1);function jn(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=he([new Uint8Array(e-t.length),t])}return B(t,"base64url")}function on(r){let e=Vf(r);return new Rb.default.jsbn.BigInteger(B(e,"base16"),16)}function Vf(r,e){let t=q(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=he([new Uint8Array(e-t.length),t])}return t}var Ib={"P-256":256,"P-384":384,"P-521":521},yB=Object.keys(Ib),B3=yB.join(" / ");async function Tb(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${B3}`,"ERR_INVALID_CURVE");let e=await Kt.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,o)=>{let a;o!=null?a=await Kt.get().subtle.importKey("jwk",bB(r,o),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await Kt.get().subtle.importKey("jwk",Cb(r,s),{name:"ECDH",namedCurve:r},!1,[]),u=await Kt.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,Ib[r]);return new Uint8Array(u,0,u.byteLength)},n=await Kt.get().subtle.exportKey("jwk",e.publicKey);return{key:wB(n),genSharedKey:t}}var Db={"P-256":32,"P-384":48,"P-521":66};function wB(r){if(r.crv==null||r.x==null||r.y==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new w(`Unknown curve: ${r.crv}. Must be ${B3}`,"ERR_INVALID_CURVE");let e=Db[r.crv];return he([Uint8Array.from([4]),Vf(r.x,e),Vf(r.y,e)],1+e*2)}function Cb(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new w(`Unknown curve: ${r}. Must be ${B3}`,"ERR_INVALID_CURVE");let t=Db[r];if(!pe(e.subarray(0,1),Uint8Array.from([4])))throw new w("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:B(e.subarray(1,t+1),"base64url"),y:B(e.subarray(1+t),"base64url"),ext:!0}}var bB=(r,e)=>({...Cb(r,e.public),d:B(e.private,"base64url")});var Pb=Tb;async function kb(r,e){let t=Ki.decode(r);return qf().decrypt(t,e)}var Nb={SHA1:20,SHA256:32,SHA512:64};var EB={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},vB=async(r,e)=>{let t=await Kt.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function Lb(r,e){let t=EB[r],n=await Kt.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(i){return vB(n,i)},length:Nb[r]}}var Bb={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function Mb(r,e,t){let n=Bb[r];if(n==null){let b=Object.keys(Bb).join(" / ");throw new w(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new w("missing hash type","ERR_MISSING_HASH_TYPE");let i=n.keySize,s=n.ivSize,o=20,a=q("key expansion"),c=2*(s+i+o),u=await Lb(e,t),l=await u.digest(a),h=[],f=0;for(;f<c;){let b=await u.digest(he([l,a])),E=b.length;f+E>c&&(E=c-f),h.push(b),f+=E,l=await u.digest(l)}let d=c/2,p=he(h),m=p.subarray(0,d),g=p.subarray(d,c),y=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+i),macKey:b.subarray(s+i)});return{k1:y(m),k2:y(g)}}var W3={};Ae(W3,{RsaPrivateKey:()=>Ya,RsaPublicKey:()=>tl,fromJwk:()=>GB,generateKeyPair:()=>WB,unmarshalRsaPrivateKey:()=>HB,unmarshalRsaPublicKey:()=>$B});var el=F(rt(),1);var Ere=F(Vb(),1);var _B=F(Ns(),1);var Le=BigInt(0),yt=BigInt(1),Vs=BigInt(2),ju=BigInt(3),zb=BigInt(8),Pt=Object.freeze({a:Le,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:yt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Hb=(r,e)=>(r+e/Vs)/e,zf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(r){let{n:e}=Pt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-yt*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=BigInt("0x100000000000000000000000000000000"),a=Hb(s*r,e),c=Hb(-n*r,e),u=$(r-a*t-c*i,e),l=$(-a*n-c*s,e),h=u>o,f=l>o;if(h&&(u=e-u),f&&(l=e-l),u>o||l>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+r);return{k1neg:h,k1:u,k2neg:f,k2:l}}},Zn=32,Ha=32,SB=32,$b=Zn+1,Gb=2*Zn+1;function Wb(r){let{a:e,b:t}=Pt,n=$(r*r),i=$(n*r);return $(i+e*r+t)}var Hf=Pt.a===Le,Wf=class extends Error{constructor(e){super(e)}};function Yb(r){if(!(r instanceof qe))throw new TypeError("JacobianPoint expected")}var qe=class{constructor(e,t,n){this.x=e,this.y=t,this.z=n}static fromAffine(e){if(!(e instanceof Xe))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Xe.ZERO)?qe.ZERO:new qe(e.x,e.y,yt)}static toAffineBatch(e){let t=DB(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(t[i]))}static normalizeZ(e){return qe.toAffineBatch(e).map(qe.fromAffine)}equals(e){Yb(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=$(i*i),u=$(a*a),l=$(t*u),h=$(s*c),f=$($(n*a)*u),d=$($(o*i)*c);return l===h&&f===d}negate(){return new qe(this.x,$(-this.y),this.z)}double(){let{x:e,y:t,z:n}=this,i=$(e*e),s=$(t*t),o=$(s*s),a=e+s,c=$(Vs*($(a*a)-i-o)),u=$(ju*i),l=$(u*u),h=$(l-Vs*c),f=$(u*(c-h)-zb*o),d=$(Vs*t*n);return new qe(h,f,d)}add(e){Yb(e);let{x:t,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===Le||o===Le)return this;if(t===Le||n===Le)return e;let c=$(i*i),u=$(a*a),l=$(t*u),h=$(s*c),f=$($(n*a)*u),d=$($(o*i)*c),p=$(h-l),m=$(d-f);if(p===Le)return m===Le?this.double():qe.ZERO;let g=$(p*p),y=$(p*g),b=$(l*g),E=$(m*m-y-Vs*b),R=$(m*(b-E)-f*y),v=$(i*a*p);return new qe(E,R,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=qe.ZERO;if(typeof e=="bigint"&&e===Le)return t;let n=jb(e);if(n===yt)return this;if(!Hf){let h=t,f=this;for(;n>Le;)n&yt&&(h=h.add(f)),f=f.double(),n>>=yt;return h}let{k1neg:i,k1:s,k2neg:o,k2:a}=zf.splitScalar(n),c=t,u=t,l=this;for(;s>Le||a>Le;)s&yt&&(c=c.add(l)),a&yt&&(u=u.add(l)),l=l.double(),s>>=yt,a>>=yt;return i&&(c=c.negate()),o&&(u=u.negate()),u=new qe($(u.x*zf.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let t=Hf?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<t;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t){!t&&this.equals(qe.BASE)&&(t=Xe.BASE);let n=t&&t._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=t&&K3.get(t);i||(i=this.precomputeWindow(n),t&&n!==1&&(i=qe.normalizeZ(i),K3.set(t,i)));let s=qe.ZERO,o=qe.BASE,a=1+(Hf?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),l=2**n,h=BigInt(n);for(let f=0;f<a;f++){let d=f*c,p=Number(e&u);e>>=h,p>c&&(p-=l,e+=yt);let m=d,g=d+Math.abs(p)-1,y=f%2!==0,b=p<0;p===0?o=o.add($f(y,i[m])):s=s.add($f(b,i[g]))}return{p:s,f:o}}multiply(e,t){let n=jb(e),i,s;if(Hf){let{k1neg:o,k1:a,k2neg:c,k2:u}=zf.splitScalar(n),{p:l,f:h}=this.wNAF(a,t),{p:f,f:d}=this.wNAF(u,t);l=$f(o,l),f=$f(c,f),f=new qe($(f.x*zf.beta),f.y,f.z),i=l.add(f),s=h.add(d)}else{let{p:o,f:a}=this.wNAF(n,t);i=o,s=a}return qe.normalizeZ([i,s])[0]}toAffine(e){let{x:t,y:n,z:i}=this,s=this.equals(qe.ZERO);e==null&&(e=s?zb:Wa(i));let o=e,a=$(o*o),c=$(a*o),u=$(t*a),l=$(n*c),h=$(i*o);if(s)return Xe.ZERO;if(h!==yt)throw new Error("invZ was invalid");return new Xe(u,l)}};qe.BASE=new qe(Pt.Gx,Pt.Gy,yt);qe.ZERO=new qe(Le,yt,Le);function $f(r,e){let t=e.negate();return r?t:e}var K3=new WeakMap,Xe=class{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,K3.delete(this)}hasEvenY(){return this.y%Vs===Le}static fromCompressedHex(e){let t=e.length===32,n=zs(t?e:e.subarray(1));if(!F3(n))throw new Error("Point is not on curve");let i=Wb(n),s=TB(i),o=(s&yt)===yt;t?o&&(s=$(-s)):(e[0]&1)===1!==o&&(s=$(-s));let a=new Xe(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let t=zs(e.subarray(1,Zn+1)),n=zs(e.subarray(Zn+1,Zn*2+1)),i=new Xe(t,n);return i.assertValidity(),i}static fromHex(e){let t=Ga(e),n=t.length,i=t[0];if(n===Zn)return this.fromCompressedHex(t);if(n===$b&&(i===2||i===3))return this.fromCompressedHex(t);if(n===Gb&&i===4)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${$b} compressed bytes or ${Gb} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return Xe.BASE.multiply(Qf(e))}static fromSignature(e,t,n){let{r:i,s}=Zb(t);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=z3(Ga(e)),{n:a}=Pt,c=n===2||n===3?i+a:i,u=Wa(c,a),l=$(-o*u,a),h=$(s*u,a),f=n&1?"03":"02",d=Xe.fromHex(f+Va(c)),p=Xe.BASE.multiplyAndAddUnsafe(d,l,h);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Mo(this.toHex(e))}toHex(e=!1){let t=Va(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Va(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(!F3(t)||!F3(n))throw new Error(e);let i=$(n*n),s=Wb(t);if($(i-s)!==Le)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Xe(this.x,$(-this.y))}double(){return qe.fromAffine(this).double().toAffine()}add(e){return qe.fromAffine(this).add(qe.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return qe.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,n){let i=qe.fromAffine(this),s=t===Le||t===yt||this!==Xe.BASE?i.multiplyUnsafe(t):i.multiply(t),o=qe.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(qe.ZERO)?void 0:a.toAffine()}};Xe.BASE=new Xe(Pt.Gx,Pt.Gy);Xe.ZERO=new Xe(Le,Le);function Qb(r){return Number.parseInt(r[0],16)>=8?"00"+r:r}function Xb(r){if(r.length<2||r[0]!==2)throw new Error(`Invalid signature integer tag: ${$a(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:zs(t),left:r.subarray(e+2)}}function AB(r){if(r.length<2||r[0]!=48)throw new Error(`Invalid signature tag: ${$a(r)}`);if(r[1]!==r.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:t}=Xb(r.subarray(2)),{data:n,left:i}=Xb(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${$a(i)}`);return{r:e,s:n}}var Ri=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?$a(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Ri(Yf(i.slice(0,64)),Yf(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}=AB(t?e:Mo(e));return new Ri(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!Ju(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Ju(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Pt.n>>yt;return this.s>e}normalizeS(){return this.hasHighS()?new Ri(this.r,$(-this.s,Pt.n)):this}toDERRawBytes(){return Mo(this.toDERHex())}toDERHex(){let e=Qb(Xu(this.s)),t=Qb(Xu(this.r)),n=e.length/2,i=t.length/2,s=Xu(n),o=Xu(i);return`30${Xu(i+n+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Mo(this.toCompactHex())}toCompactHex(){return Va(this.r)+Va(this.s)}};function qs(...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;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return t}var RB=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function $a(r){if(!(r instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;t<r.length;t++)e+=RB[r[t]];return e}var IB=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Va(r){if(typeof r!="bigint")throw new Error("Expected bigint");if(!(Le<=r&&r<IB))throw new Error("Expected number 0 <= n < 2^256");return r.toString(16).padStart(64,"0")}function q3(r){let e=Mo(Va(r));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function Xu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Yf(r){if(typeof r!="string")throw new TypeError("hexToNumber: expected string, got "+typeof r);return BigInt(`0x${r}`)}function Mo(r){if(typeof r!="string")throw new TypeError("hexToBytes: expected string, got "+typeof r);if(r.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+r.length);let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++){let n=t*2,i=r.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[t]=s}return e}function zs(r){return Yf($a(r))}function Ga(r){return r instanceof Uint8Array?Uint8Array.from(r):Mo(r)}function jb(r){if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)return BigInt(r);if(typeof r=="bigint"&&Ju(r))return r;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function $(r,e=Pt.P){let t=r%e;return t>=Le?t:e+t}function Dn(r,e){let{P:t}=Pt,n=r;for(;e-- >Le;)n*=n,n%=t;return n}function TB(r){let{P:e}=Pt,t=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=r*r*r%e,u=c*c*r%e,l=Dn(u,ju)*u%e,h=Dn(l,ju)*u%e,f=Dn(h,Vs)*c%e,d=Dn(f,n)*f%e,p=Dn(d,i)*d%e,m=Dn(p,o)*p%e,g=Dn(m,a)*m%e,y=Dn(g,o)*p%e,b=Dn(y,ju)*u%e,E=Dn(b,s)*d%e,R=Dn(E,t)*c%e,v=Dn(R,Vs);if(v*v%e!==r)throw new Error("Cannot find square root");return v}function Wa(r,e=Pt.P){if(r===Le||e<=Le)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=$(r,e),n=e,i=Le,s=yt,o=yt,a=Le;for(;t!==Le;){let u=n/t,l=n%t,h=i-o*u,f=s-a*u;n=t,t=l,i=o,s=a,o=h,a=f}if(n!==yt)throw new Error("invert: does not exist");return $(i,e)}function DB(r,e=Pt.P){let t=new Array(r.length),n=r.reduce((s,o,a)=>o===Le?s:(t[a]=s,$(s*o,e)),yt),i=Wa(n,e);return r.reduceRight((s,o,a)=>o===Le?s:(t[a]=$(s*t[a],e),$(s*o,e)),i),t}function CB(r){let e=r.length*8-Ha*8,t=zs(r);return e>0?t>>BigInt(e):t}function z3(r,e=!1){let t=CB(r);if(e)return t;let{n}=Pt;return t>=n?t-n:t}var za,Zu,V3=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 Jn.hmacSha256(this.k,...e)}hmacSync(...e){return Zu(this.k,...e)}checkSync(){if(typeof Zu!="function")throw new Wf("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(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return qs(...t)}generateSync(){this.checkSync(),this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();t.push(n),e+=this.v.length}return qs(...t)}};function Ju(r){return Le<r&&r<Pt.n}function F3(r){return Le<r&&r<Pt.P}function PB(r,e,t,n=!0){let{n:i}=Pt,s=z3(r,!0);if(!Ju(s))return;let o=Wa(s,i),a=Xe.BASE.multiply(s),c=$(a.x,i);if(c===Le)return;let u=$(o*$(e+t*c,i),i);if(u===Le)return;let l=new Ri(c,u),h=(a.x===l.r?0:2)|Number(a.y&yt);return n&&l.hasHighS()&&(l=l.normalizeS(),h^=1),{sig:l,recovery:h}}function Qf(r){let e;if(typeof r=="bigint")e=r;else if(typeof r=="number"&&Number.isSafeInteger(r)&&r>0)e=BigInt(r);else if(typeof r=="string"){if(r.length!==2*Ha)throw new Error("Expected 32 bytes of private key");e=Yf(r)}else if(r instanceof Uint8Array){if(r.length!==Ha)throw new Error("Expected 32 bytes of private key");e=zs(r)}else throw new TypeError("Expected valid private key");if(!Ju(e))throw new Error("Expected private key: 0 < key < n");return e}function kB(r){return r instanceof Xe?(r.assertValidity(),r):Xe.fromHex(r)}function Zb(r){if(r instanceof Ri)return r.assertValidity(),r;try{return Ri.fromDER(r)}catch{return Ri.fromCompact(r)}}function H3(r,e=!1){return Xe.fromPrivateKey(r).toRawBytes(e)}function Jb(r){let e=r.length>Zn?r.slice(0,Zn):r;return zs(e)}function NB(r){let e=Jb(r),t=$(e,Pt.n);return eE(t<Le?e:t)}function eE(r){return q3(r)}function LB(r,e,t){if(r==null)throw new Error(`sign: expected valid message hash, not "${r}"`);let n=Ga(r),i=Qf(e),s=[eE(i),NB(n)];if(t!=null){t===!0&&(t=Jn.randomBytes(Zn));let c=Ga(t);if(c.length!==Zn)throw new Error(`sign: Expected ${Zn} bytes of extra data`);s.push(c)}let o=qs(...s),a=Jb(n);return{seed:o,m:a,d:i}}function OB(r,e){let{sig:t,recovery:n}=r,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?t.toDERRawBytes():t.toCompactRawBytes();return s?[o,n]:o}async function tE(r,e,t={}){let{seed:n,m:i,d:s}=LB(r,e,t.extraEntropy),o=new V3(SB,Ha);await o.reseed(n);let a;for(;!(a=PB(await o.generate(),i,s,t.canonical));)await o.reseed();return OB(a,t)}var BB={strict:!0};function rE(r,e,t,n=BB){let i;try{i=Zb(r),e=Ga(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=z3(e),c;try{c=kB(t)}catch{return!1}let{n:u}=Pt,l=Wa(o,u),h=$(a*l,u),f=$(s*l,u),d=Xe.BASE.multiplyAndAddUnsafe(c,h,f);return d?$(d.x,u)===s:!1}Xe.BASE._setWindowSize(8);var an={node:_B,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var Gf={},Jn={bytesToHex:$a,hexToBytes:Mo,concatBytes:qs,mod:$,invert:Wa,isValidPrivateKey(r){try{return Qf(r),!0}catch{return!1}},_bigintTo32Bytes:q3,_normalizePrivateKey:Qf,hashToPrivateKey:r=>{r=Ga(r);let e=Ha+8;if(r.length<e||r.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let t=$(zs(r),Pt.n-yt)+yt;return q3(t)},randomBytes:(r=32)=>{if(an.web)return an.web.getRandomValues(new Uint8Array(r));if(an.node){let{randomBytes:e}=an.node;return Uint8Array.from(e(r))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Jn.hashToPrivateKey(Jn.randomBytes(Ha+8)),precompute(r=8,e=Xe.BASE){let t=e===Xe.BASE?e:new Xe(e.x,e.y);return t._setWindowSize(r),t.multiply(ju),t},sha256:async(...r)=>{if(an.web){let e=await an.web.subtle.digest("SHA-256",qs(...r));return new Uint8Array(e)}else if(an.node){let{createHash:e}=an.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(an.web){let t=await an.web.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=qs(...e),i=await an.web.subtle.sign("HMAC",t,n);return new Uint8Array(i)}else if(an.node){let{createHmac:t}=an.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=Gf[r];if(t===void 0){let n=await Jn.sha256(Uint8Array.from(r,i=>i.charCodeAt(0)));t=qs(n,n),Gf[r]=t}return Jn.sha256(t,...e)},taggedHashSync:(r,...e)=>{if(typeof za!="function")throw new Wf("sha256Sync is undefined, you need to set it");let t=Gf[r];if(t===void 0){let n=za(Uint8Array.from(r,i=>i.charCodeAt(0)));t=qs(n,n),Gf[r]=t}return za(t,...e)},_JacobianPoint:qe};Object.defineProperties(Jn,{sha256Sync:{configurable:!1,get(){return za},set(r){za||(za=r)}},hmacSha256Sync:{configurable:!1,get(){return Zu},set(r){Zu||(Zu=r)}}});function Cn(r){if(isNaN(r)||r<=0)throw new w("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Jn.randomBytes(r)}var rre=F(Of(),1),$3=F(rt(),1);function nE(r,e){return e.map(t=>on(r[t]))}function iE(r){return $3.default.pki.setRsaPrivateKey(...nE(r,["n","e","d","p","q","dp","dq","qi"]))}function sE(r){return $3.default.pki.setRsaPublicKey(...nE(r,["n","e"]))}var Uo={};Ae(Uo,{jwkToPkcs1:()=>FB,jwkToPkix:()=>qB,pkcs1ToJwk:()=>UB,pkixToJwk:()=>KB});var sre=F(qu(),1),ore=F(Of(),1);var Ji=F(rt(),1);function UB(r){let e=Ji.default.asn1.fromDer(B(r,"ascii")),t=Ji.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:jn(t.n),e:jn(t.e),d:jn(t.d),p:jn(t.p),q:jn(t.q),dp:jn(t.dP),dq:jn(t.dQ),qi:jn(t.qInv),alg:"RS256"}}function FB(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 w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.privateKeyToAsn1({n:on(r.n),e:on(r.e),d:on(r.d),p:on(r.p),q:on(r.q),dP:on(r.dp),dQ:on(r.dq),qInv:on(r.qi)});return q(Ji.default.asn1.toDer(e).getBytes(),"ascii")}function KB(r){let e=Ji.default.asn1.fromDer(B(r,"ascii")),t=Ji.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:jn(t.n),e:jn(t.e)}}function qB(r){if(r.n==null||r.e==null)throw new w("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Ji.default.pki.publicKeyToAsn1({n:on(r.n),e:on(r.e)});return q(Ji.default.asn1.toDer(e).getBytes(),"ascii")}async function oE(r){let e=await Kt.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 uE(e);return{privateKey:t[0],publicKey:t[1]}}async function G3(r){let t=[await Kt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await VB(r)],n=await uE({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function aE(r,e){let t=await Kt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Kt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function cE(r,e,t){let n=await Kt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Kt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t)}async function uE(r){if(r.privateKey==null||r.publicKey==null)throw new w("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Kt.get().subtle.exportKey("jwk",r.privateKey),Kt.get().subtle.exportKey("jwk",r.publicKey)])}async function VB(r){return Kt.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 lE(r,e,t,n){let i=e?sE(r):iE(r),s=B(Uint8Array.from(t),"ascii"),o=n(s,i);return q(o,"ascii")}function hE(r,e){return lE(r,!0,e,(t,n)=>n.encrypt(t))}function fE(r,e){return lE(r,!1,e,(t,n)=>n.decrypt(t))}var tl=class{_key;constructor(e){this._key=e}async verify(e,t){return cE(this._key,t,e)}marshal(){return Uo.jwkToPkix(this._key)}get bytes(){return Qn.encode({Type:mt.RSA,Data:this.marshal()}).subarray()}encrypt(e){return hE(this._key,e)}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}},Ya=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Cn(16)}async sign(e){return aE(this._key,e)}get public(){if(this._publicKey==null)throw new w("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new tl(this._publicKey)}decrypt(e){return fE(this._key,e)}marshal(){return Uo.jwkToPkcs1(this._key)}get bytes(){return Xn.encode({Type:mt.RSA,Data:this.marshal()}).subarray()}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}async id(){let e=await this.public.hash();return B(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8"){let n=new el.default.util.ByteBuffer(this.marshal()),i=el.default.asn1.fromDer(n),s=el.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return el.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(t==="libp2p-key")return Fa(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function HB(r){let e=Uo.pkcs1ToJwk(r),t=await G3(e);return new Ya(t.privateKey,t.publicKey)}function $B(r){let e=Uo.pkixToJwk(r);return new tl(e)}async function GB(r){let e=await G3(r);return new Ya(e.privateKey,e.publicKey)}async function WB(r){let e=await oE(r);return new Ya(e.privateKey,e.publicKey)}var Q3={};Ae(Q3,{Secp256k1PrivateKey:()=>nl,Secp256k1PublicKey:()=>rl,generateKeyPair:()=>jB,unmarshalSecp256k1PrivateKey:()=>QB,unmarshalSecp256k1PublicKey:()=>XB});function dE(){return Jn.randomPrivateKey()}async function pE(r,e){let{digest:t}=await Pe.digest(e);try{return await tE(t,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}async function mE(r,e,t){try{let{digest:n}=await Pe.digest(t);return rE(e,n,r)}catch(n){throw new w(String(n),"ERR_INVALID_INPUT")}}function gE(r){return Xe.fromHex(r).toRawBytes(!0)}function yE(r){try{H3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Y3(r){try{Xe.fromHex(r)}catch(e){throw new w(String(e),"ERR_INVALID_PUBLIC_KEY")}}function wE(r){try{return H3(r,!0)}catch(e){throw new w(String(e),"ERR_INVALID_PRIVATE_KEY")}}var rl=class{_key;constructor(e){Y3(e),this._key=e}async verify(e,t){return mE(this._key,t,e)}marshal(){return gE(this._key)}get bytes(){return Qn.encode({Type:mt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}},nl=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??wE(e),yE(this._key),Y3(this._publicKey)}async sign(e){return pE(this._key,e)}get public(){return new rl(this._publicKey)}marshal(){return this._key}get bytes(){return Xn.encode({Type:mt.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return pe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await Pe.digest(this.bytes);return e}async id(){let e=await this.public.hash();return B(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Fa(this.bytes,e);throw new w(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function QB(r){return new nl(r)}function XB(r){return new rl(r)}async function jB(){let r=dE();return new nl(r)}var Ii={rsa:W3,ed25519:O3,secp256k1:Q3};function X3(r){let e=Object.keys(Ii).join(" / ");return new w(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function j3(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Ii[r];throw X3(r)}async function il(r,e){return j3(r).generateKeyPair(e??2048)}async function ZB(r,e,t){if(r.toLowerCase()!=="ed25519")throw new w("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return L3(e)}function kr(r){let e=Qn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case mt.RSA:return Ii.rsa.unmarshalRsaPublicKey(t);case mt.Ed25519:return Ii.ed25519.unmarshalEd25519PublicKey(t);case mt.Secp256k1:return Ii.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw X3(e.Type??"RSA")}}function Qa(r,e){return e=(e??"rsa").toLowerCase(),j3(e),r.bytes}async function cn(r){let e=Xn.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case mt.RSA:return Ii.rsa.unmarshalRsaPrivateKey(t);case mt.Ed25519:return Ii.ed25519.unmarshalEd25519PrivateKey(t);case mt.Secp256k1:return Ii.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw X3(e.Type??"RSA")}}function Z3(r,e){return e=(e??"rsa").toLowerCase(),j3(e),r.bytes}async function Xa(r,e){try{let i=await kb(r,e);return await cn(i)}catch{}let t=Xf.default.pki.decryptRsaPrivateKey(r,e);if(t===null)throw new w("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Xf.default.asn1.toDer(Xf.default.pki.privateKeyToAsn1(t));return n=q(n.getBytes(),"ascii"),Ii.rsa.unmarshalRsaPrivateKey(n)}var Fo="StrictSign",ja="StrictNoSign",ei;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(ei||(ei={}));var bE;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(bE||(bE={}));var Hs;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(Hs||(Hs={}));var Nr;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Nr||(Nr={}));var xr;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(xr||(xr={}));var Pn;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(Pn||(Pn={}));function J3(r){switch(r){case ei.Ignore:return Nr.Ignore;case ei.Reject:return Nr.Reject}}async function em(r,e){switch(r){case Fo:{if(!e)throw Error("Must provide PeerId");if(e.privateKey==null)throw Error("Cannot sign message, no private key present");if(e.publicKey==null)throw Error("Cannot sign message, no public key present");let t=await cn(e.privateKey);return{type:Hs.Signing,author:e,key:e.publicKey,privateKey:t}}case ja:return{type:Hs.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var ot="ERR_INVALID_PEER_SCORE_PARAMS";var JB={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},eM={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 EE(r={}){return{...JB,...r,topics:r.topics?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=tM(n),e),{}):{}}}function tM(r={}){return{...eM,...r}}function vE(r){for(let[e,t]of Object.entries(r.topics))try{rM(t)}catch(n){throw new w(`invalid score parameters for topic ${e}: ${n.message}`,ot)}if(r.topicScoreCap<0)throw new w("invalid topic score cap; must be positive (or 0 for no cap)",ot);if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new w("missing application specific score function",ot);if(r.IPColocationFactorWeight>0)throw new w("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",ot);if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new w("invalid IPColocationFactorThreshold; must be at least 1",ot);if(r.behaviourPenaltyWeight>0)throw new w("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",ot);if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new w("invalid BehaviourPenaltyDecay; must be between 0 and 1",ot);if(r.decayInterval<1e3)throw new w("invalid DecayInterval; must be at least 1s",ot);if(r.decayToZero<=0||r.decayToZero>=1)throw new w("invalid DecayToZero; must be between 0 and 1",ot)}function rM(r){if(r.topicWeight<0)throw new w("invalid topic weight; must be >= 0",ot);if(r.timeInMeshQuantum===0)throw new w("invalid TimeInMeshQuantum; must be non zero",ot);if(r.timeInMeshWeight<0)throw new w("invalid TimeInMeshWeight; must be positive (or 0 to disable)",ot);if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new w("invalid TimeInMeshQuantum; must be positive",ot);if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new w("invalid TimeInMeshCap; must be positive",ot);if(r.firstMessageDeliveriesWeight<0)throw new w("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",ot);if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new w("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",ot);if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new w("invalid FirstMessageDeliveriesCap; must be positive",ot);if(r.meshMessageDeliveriesWeight>0)throw new w("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",ot);if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new w("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",ot);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new w("invalid MeshMessageDeliveriesCap; must be positive",ot);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new w("invalid MeshMessageDeliveriesThreshold; must be positive",ot);if(r.meshMessageDeliveriesWindow<0)throw new w("invalid MeshMessageDeliveriesWindow; must be non-negative",ot);if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new w("invalid MeshMessageDeliveriesActivation; must be at least 1s",ot);if(r.meshFailurePenaltyWeight>0)throw new w("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",ot);if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new w("invalid MeshFailurePenaltyDecay; must be between 0 and 1",ot);if(r.invalidMessageDeliveriesWeight>0)throw new w("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",ot);if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new w("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",ot)}var nM={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function xE(r={}){return{...nM,...r}}function _E(r,e,t,n){let i=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];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.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let d=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,p=d*d;u+=p*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;u+=h*c.meshFailurePenaltyWeight;let f=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=f*c.invalidMessageDeliveriesWeight,i+=u*c.topicWeight}),t.topicScoreCap>0&&i>t.topicScoreCap&&(i=t.topicScoreCap);let s=t.appSpecificScore(r);if(i+=s*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=n.get(o),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 o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;i+=a*t.behaviourPenaltyWeight}return i}var RE=F(AE(),1),Lr;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Lr||(Lr={}));var Zf=class{constructor(){this.records=new Map,this.queue=new RE.default}ensureRecord(e){let t=this.records.get(e);if(t)return t;t={status:Lr.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<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};function e0(r,e,t=()=>!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 IE(r,e){return e0(r,e,()=>!0)}var Jf=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 Za=D("libp2p:gossipsub:score"),t0=class{constructor(e,t,n){this.params=e,this.metrics=t,this.peerStats=new Map,this.peerIPs=new Jf(()=>new Set),this.scoreCache=new Map,this.deliveryRecords=new Zf,vE(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??_E}get size(){return this.peerStats.size}start(){if(this._backgroundInterval){Za("Peer score already running");return}this._backgroundInterval=setInterval(()=>this.background(),this.params.decayInterval),Za("started")}stop(){if(!this._backgroundInterval){Za("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),Za("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(([s,o])=>{let a=this.params.topics[s];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveries<t&&(o.firstMessageDeliveries=0),o.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,o.meshMessageDeliveries<t&&(o.meshMessageDeliveries=0),o.meshFailurePenalty*=a.meshFailurePenaltyDecay,o.meshFailurePenalty<t&&(o.meshFailurePenalty=0),o.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,o.invalidMessageDeliveries<t&&(o.invalidMessageDeliveries=0),o.inMesh&&(o.meshTime=e-o.graftTime,o.meshTime>a.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(!t)return 0;let n=Date.now(),i=this.scoreCache.get(e);if(i&&i.cacheUntil>n)return i.score;this.metrics?.scoreFnRuns.inc();let s=this.computeScore(e,t,this.params,this.peerIPs),o=n+this.scoreCacheValidityMs;return i?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-i.score)),i.score=s,i.cacheUntil=o):this.scoreCache.set(e,{score:s,cacheUntil:o}),s}addPenalty(e,t,n){let i=this.peerStats.get(e);i&&(i.behaviourPenalty+=t,this.metrics?.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 s=this.params.topics[n].meshMessageDeliveriesThreshold;if(i.inMesh&&i.meshMessageDeliveriesActive&&i.meshMessageDeliveries<s){let o=s-i.meshMessageDeliveries;i.meshFailurePenalty+=o*o}i.inMesh=!1,i.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);i&&(i.inMesh=!0,i.graftTime=Date.now(),i.meshTime=0,i.meshMessageDeliveriesActive=!1)}}prune(e,t){let n=this.peerStats.get(e);if(n){let i=this.getPtopicStats(n,t);if(i){let s=this.params.topics[t].meshMessageDeliveriesThreshold;if(i.meshMessageDeliveriesActive&&i.meshMessageDeliveries<s){let o=s-i.meshMessageDeliveries;i.meshFailurePenalty+=o*o}i.meshMessageDeliveriesActive=!1,i.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);let i=this.deliveryRecords.ensureRecord(t),s=Date.now();if(i.status!==Lr.unknown){Za("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-i.firstSeen,Lr[i.status]);return}i.status=Lr.valid,i.validated=s,i.peers.forEach(o=>{o!==e.toString()&&this.markDuplicateMessageDelivery(o,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,i){switch(i){case Nr.Error:this.markInvalidMessageDelivery(e,n);return;case Nr.Blacklisted:return}let s=this.deliveryRecords.ensureRecord(t);if(s.status!==Lr.unknown){Za("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeen,Lr[s.status]);return}if(i===Nr.Ignore){s.status=Lr.ignored,s.peers.clear();return}s.status=Lr.invalid,this.markInvalidMessageDelivery(e,n),s.peers.forEach(o=>{this.markInvalidMessageDelivery(o,n)}),s.peers.clear()}duplicateMessage(e,t,n){let i=this.deliveryRecords.ensureRecord(t);if(!i.peers.has(e))switch(i.status){case Lr.unknown:i.peers.add(e);break;case Lr.valid:i.peers.add(e),this.markDuplicateMessageDelivery(e,n,i.validated);break;case Lr.invalid:this.markInvalidMessageDelivery(e,n);break;case Lr.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 s=this.params.topics[t].firstMessageDeliveriesCap;i.firstMessageDeliveries=Math.min(s,i.firstMessageDeliveries+1),i.inMesh&&(s=this.params.topics[t].meshMessageDeliveriesCap,i.meshMessageDeliveries=Math.min(s,i.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let i=this.peerStats.get(e);if(i){let s=n!==void 0?Date.now():0,o=this.getPtopicStats(i,t);if(o&&o.inMesh){let a=this.params.topics[t];if(n!==void 0){let u=s-n,l=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,l),l)return}let c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,o.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 r0=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],s=this.msgIdToStrFn(i),o=this.promises.get(s);o||(o=new Map,this.promises.set(s,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(s)||this.requestMsByMsg.set(s,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((i,s)=>{i.forEach((o,a)=>{o<e&&(t.set(a,(t.get(a)??0)+1),i.delete(a),n++)}),i.size||this.promises.delete(s)}),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);let n=this.promises.get(e);n&&(this.promises.delete(e),this.metrics&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Nr.Error:return}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[n,i]of this.requestMsByMsg.entries())if(i<e)this.requestMsByMsg.delete(n),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Ja=class{constructor(e){this.entries=new Map,this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,n]of this.entries.entries())if(n.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var TE;(function(r){r.forward="forward",r.publish="publish"})(TE||(TE={}));var es;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(es||(es={}));var Ko;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Unsub="unsubscribed",r.Excess="excess"})(Ko||(Ko={}));var tc;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(tc||(tc={}));var rc;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(rc||(rc={}));var ec;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(ec||(ec={}));function DE(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,s){let o=this.toTopic(n);this.meshPeerInclusionEvents.inc({topic:o,reason:i},s)},onRemoveFromMesh(n,i,s){let o=this.toTopic(n);this.meshPeerChurnEvents.inc({topic:o,reason:i},s)},onReportValidationMcacheHit(n){this.asyncValidationMcacheHit.inc({hit:n?"hit":"miss"})},onReportValidation(n,i){let s=this.toTopic(n);this.asyncValidationResult.inc({topic:s,acceptance:i})},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,i,s){let o=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:o},i),this.ihaveRcvNotSeenMsgids.inc({topic:o},s)},onIwantRcv(n,i){for(let[s,o]of n){let a=this.toTopic(s);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(i)},onForwardMsg(n,i){let s=this.toTopic(n);this.msgForwardCount.inc({topic:s},1),this.msgForwardPeers.inc({topic:s},i)},onPublishMsg(n,i,s,o){let a=this.toTopic(n);this.msgPublishCount.inc({topic:a},1),this.msgPublishBytes.inc({topic:a},s*o),this.msgPublishPeers.inc({topic:a},s),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 s=this.toTopic(n);this.msgReceivedStatus.inc({topic:s,status:i})},onMsgRecvInvalid(n,i){let s=this.toTopic(n),o=i.reason===Nr.Error?i.error:i.reason;this.msgReceivedInvalid.inc({topic:s,error:o},1)},onDuplicateMsgDelivery(n,i,s){if(this.duplicateMsgDeliveryDelay.observe(i/1e3),s){let o=this.toTopic(n);this.duplicateMsgLateDelivery.inc({topic:o},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){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 s=n.control.ihave?.length??0,o=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0;s>0&&this.rpcSentIHave.inc(s),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),(s>0||o>0||a>0||c>0)&&this.rpcSentControl.inc(1)}},registerScores(n,i){let s=0,o=0,a=0,c=0;for(let u of n)u>=i.graylistThreshold&&s++,u>=i.publishThreshold&&o++,u>=i.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:ec.graylist},s),this.peersByScoreThreshold.set({threshold:ec.publish},o),this.peersByScoreThreshold.set({threshold:ec.gossip},a),this.peersByScoreThreshold.set({threshold:ec.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[i,s]of n.byTopic)this.scoreWeights.set({topic:i,p:"p1"},s.p1w),this.scoreWeights.set({topic:i,p:"p2"},s.p2w),this.scoreWeights.set({topic:i,p:"p3"},s.p3w),this.scoreWeights.set({topic:i,p:"p3b"},s.p3bw),this.scoreWeights.set({topic:i,p:"p4"},s.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 s=new Map;n.forEach((o,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",u=s.get(c);u||(u=new Set,s.set(c,u)),o.forEach(l=>u?.add(l))});for(let[o,a]of s){let c=[];a.forEach(u=>{c.push(i.get(u)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var Ane=F(Sf(),1),sM=F(rt(),1);var PE=F(p3(),1),kE=F(Ft(),1),CE={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function sl(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(CE).join(" / ");throw new w(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=CE[i],o=(0,PE.default)(r,e,t,n,s);return kE.default.encode64(o,null)}var NE=q("libp2p-pubsub:");async function LE(r,e,t,n){switch(r.type){case Hs.Signing:{let i={from:r.author.toBytes(),data:n,seqno:Cn(8),topic:e,signature:void 0,key:void 0},s=he([NE,Mu.Message.encode(i).finish()]);i.signature=await r.privateKey.sign(s),i.key=r.key;let o={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${B(i.seqno,"base16")}`),topic:e,signature:i.signature,key:i.key};return{raw:i,msg:o}}case Hs.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 OE(r,e){switch(r){case ja:return e.signature!=null?{valid:!1,error:xr.SignaturePresent}:e.seqno!=null?{valid:!1,error:xr.SeqnoPresent}:e.key!=null?{valid:!1,error:xr.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Fo:{if(e.seqno==null)return{valid:!1,error:xr.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:xr.InvalidSeqno};if(e.signature==null)return{valid:!1,error:xr.InvalidSignature};if(e.from==null)return{valid:!1,error:xr.InvalidPeerId};let t;try{t=It(e.from)}catch{return{valid:!1,error:xr.InvalidPeerId}}let n;if(e.key){if(n=kr(e.key),t.publicKey!==void 0&&!pe(n.bytes,t.publicKey))return{valid:!1,error:xr.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:xr.InvalidPeerId};n=kr(t.publicKey)}let i={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},s=he([NE,Mu.Message.encode(i).finish()]);return await n.verify(s,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${B(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key??Qa(n)}}:{valid:!1,error:xr.InvalidSignature}}}}var BE=(r,e)=>{let t=q(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 ME(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return BE(r.from.toBytes(),r.sequenceNumber)}async function UE(r){return await Pe.encode(r.data)}function cM(r,e,t,n,i){let s=0,o=new Map;if(Object.entries(e.topics).forEach(([f,d])=>{let p=i.get(f)??"unknown",m=t.topics[f];if(m===void 0)return;let g=o.get(p);g||(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(p,g));let y=0,b=0,E=0,R=0,v=0;if(d.inMesh){let M=Math.max(d.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=M*m.timeInMeshWeight}let _=d.firstMessageDeliveries;if(_>m.firstMessageDeliveriesCap&&(_=m.firstMessageDeliveriesCap),b+=_*m.firstMessageDeliveriesWeight,d.meshMessageDeliveriesActive&&d.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let M=m.meshMessageDeliveriesThreshold-d.meshMessageDeliveries,W=M*M;E+=W*m.meshMessageDeliveriesWeight}let I=d.meshFailurePenalty;R+=I*m.meshFailurePenaltyWeight;let P=d.invalidMessageDeliveries*d.invalidMessageDeliveries;v+=P*m.invalidMessageDeliveriesWeight,s+=(y+b+E+R+v)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=E,g.p3bw+=R,g.p4w+=v}),t.topicScoreCap>0&&s>t.topicScoreCap){s=t.topicScoreCap;let f=t.topicScoreCap/s;for(let d of o.values())d.p1w*=f,d.p2w*=f,d.p3w*=f,d.p3bw*=f,d.p4w*=f}let a=0,c=0,u=0,l=t.appSpecificScore(r);a+=l*t.appSpecificWeight,e.knownIPs.forEach(f=>{if(t.IPColocationFactorWhitelist.has(f))return;let d=n.get(f),p=d?d.size:0;if(p>t.IPColocationFactorThreshold){let m=p-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return u+=h*t.behaviourPenaltyWeight,s+=a+c+u,{byTopic:o,p5w:a,p6w:c,p7w:u,score:s}}function FE(r,e,t,n,i){let s={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of r){let a=e.get(o);if(a){let c=cM(o,a,t,n,i);for(let[u,l]of c.byTopic){let h=s.byTopic.get(u);h||(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},s.byTopic.set(u,h)),h.p1w.push(l.p1w),h.p2w.push(l.p2w),h.p3w.push(l.p3w),h.p3bw.push(l.p3bw),h.p4w.push(l.p4w)}s.p5w.push(c.p5w),s.p6w.push(c.p6w),s.p7w.push(c.p7w),s.score.push(c.score)}else s.p5w.push(0),s.p6w.push(0),s.p7w.push(0),s.score.push(0)}return s}var n0=class{constructor(e,t,n){this.rawStream=e,this.pushable=tt({objectMode:!1}),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,be(lt(this.pushable,this.closeController.signal,{returnOnAbort:!0}),i=>Et(i),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()}},i0=class{constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.source=lt(be(this.rawStream,n=>Ct(n,t)),this.closeController.signal,{returnOnAbort:!0})}close(){this.closeController.abort(),this.rawStream.close()}};var KE=F(Z2(),1),qE={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};function VE(r,e){e={...e};let t=KE.default.Reader.create(r),n=r.length,i=n===void 0?t.len:t.pos+n,s={};for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.subscriptions&&s.subscriptions.length||(s.subscriptions=[]),s.subscriptions.length<e.maxSubscriptions?s.subscriptions.push(uM(t,t.uint32())):t.skipType(o&7);break;case 2:s.messages&&s.messages.length||(s.messages=[]),s.messages.length<e.maxMessages?s.messages.push(lM(t,t.uint32())):t.skipType(o&7);break;case 3:s.control=hM(t,t.uint32(),e);break;default:t.skipType(o&7);break}}return s}function uM(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos<t;){let i=r.uint32();switch(i>>>3){case 1:n.subscribe=r.bool();break;case 2:n.topic=r.string();break;default:r.skipType(i&7);break}}return n}function lM(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos<t;){let i=r.uint32();switch(i>>>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 hM(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos<n;){let s=r.uint32();switch(s>>>3){case 1:i.ihave&&i.ihave.length||(i.ihave=[]),i.ihave.length<t.maxControlMessages?i.ihave.push(fM(r,r.uint32(),t)):r.skipType(s&7);break;case 2:i.iwant&&i.iwant.length||(i.iwant=[]),i.iwant.length<t.maxControlMessages?i.iwant.push(dM(r,r.uint32(),t)):r.skipType(s&7);break;case 3:i.graft&&i.graft.length||(i.graft=[]),i.graft.length<t.maxControlMessages?i.graft.push(pM(r,r.uint32())):r.skipType(s&7);break;case 4:i.prune&&i.prune.length||(i.prune=[]),i.prune.length<t.maxControlMessages?i.prune.push(mM(r,r.uint32(),t)):r.skipType(s&7);break;default:r.skipType(s&7);break}}return i}function fM(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos<n;){let s=r.uint32();switch(s>>>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(s&7);break;default:r.skipType(s&7);break}}return i}function dM(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos<n;){let s=r.uint32();switch(s>>>3){case 1:i.messageIDs&&i.messageIDs.length||(i.messageIDs=[]),t.maxIwantMessageIDs-- >0?i.messageIDs.push(r.bytes()):r.skipType(s&7);break;default:r.skipType(s&7);break}}return i}function pM(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos<t;){let i=r.uint32();switch(i>>>3){case 1:n.topicID=r.string();break;default:r.skipType(i&7);break}}return n}function mM(r,e,t){let n=e===void 0?r.len:r.pos+e,i={};for(;r.pos<n;){let s=r.uint32();switch(s>>>3){case 1:i.topicID=r.string();break;case 2:i.peers&&i.peers.length||(i.peers=[]),t.maxPeerInfos-- >0?i.peers.push(gM(r,r.uint32())):r.skipType(s&7);break;case 3:i.backoff=r.uint64();break;default:r.skipType(s&7);break}}return i}function gM(r,e){let t=e===void 0?r.len:r.pos+e,n={};for(;r.pos<t;){let i=r.uint32();switch(i>>>3){case 1:n.peerID=r.bytes();break;case 2:n.signedPeerRecord=r.bytes();break;default:r.skipType(i&7);break}}return n}var s0=class{index=0;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 s=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=e,s+=l,s>u||(o+=1,t!==void 0&&o>t))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let i=n*2;if(n<t.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return t[i]=o[0],t[i+1]=o[1],t[i+2]=o[2],t[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];t[i]=s>>8,t[i+1]=s&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 s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var zE=45,yM=15,nc=new s0;function tm(r){if(!(r.length>yM))return nc.new(r).parseWith(()=>nc.readIPv4Addr())}function rm(r){if(!(r.length>zE))return nc.new(r).parseWith(()=>nc.readIPv6Addr())}function o0(r){if(!(r.length>zE))return nc.new(r).parseWith(()=>nc.readIPAddr())}var _ie=parseInt("0xFFFF",16),Sie=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ti=F(bo(),1);function GE(r){return!!tm(r)}function WE(r){return!!rm(r)}function ic(r){return!!o0(r)}var YE=GE,xM=WE,nm=function(r){let e=0;if(r=r.toString().trim(),YE(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(xM(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=YE(t[n]),o;s&&(o=nm(t[n]),t[n]=B(o.slice(0,2),"base16")),o!=null&&++n<8&&t.splice(n,0,B(o.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let i=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},QE=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 s=0;s<t;s++)i.push(r[e+s]);return i.join(".")}if(t===16){let i=[];for(let s=0;s<t;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ol={},im={},SM=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];SM.forEach(r=>{let e=AM(...r);im[e.code]=e,ol[e.name]=e});function AM(r,e,t,n,i){return{code:r,size:e,name:t,resolvable:!!n,path:!!i}}function X(r){if(typeof r=="number"){if(im[r]!=null)return im[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ol[r]!=null)return ol[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var ase=X("ip4"),cse=X("ip6"),use=X("ipcidr");function a0(r,e){switch(X(r).code){case 4:case 41:return IM(e);case 42:return ZE(e);case 6:case 273:case 33:case 132:return tv(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ZE(e);case 421:return PM(e);case 444:return JE(e);case 445:return JE(e);case 466:return CM(e);default:return B(e,"base16")}}function ev(r,e){switch(X(r).code){case 4:return XE(e);case 41:return XE(e);case 42:return jE(e);case 6:case 273:case 33:case 132:return om(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return jE(e);case 421:return TM(e);case 444:return kM(e);case 445:return NM(e);case 466:return DM(e);default:return q(e,"base16")}}var sm=Object.values(En).map(r=>r.decoder),RM=function(){let r=sm[0].or(sm[1]);return sm.slice(2).forEach(e=>r=r.or(e)),r}();function XE(r){if(!ic(r))throw new Error("invalid ip address");return nm(r)}function IM(r){let e=QE(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ic(e))throw new Error("invalid ip address");return e}function om(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function tv(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function jE(r){let e=q(r),t=Uint8Array.from(Ti.default.encode(e.length));return he([t,e],t.length+e.length)}function ZE(r){let e=Ti.default.decode(r);if(r=r.slice(Ti.default.decode.bytes),r.length!==e)throw new Error("inconsistent lengths");return B(r)}function TM(r){let e;r[0]==="Q"||r[0]==="1"?e=ui(me.decode(`z${r}`)).bytes:e=ee.parse(r).multihash.bytes;let t=Uint8Array.from(Ti.default.encode(e.length));return he([t,e],t.length+e.length)}function DM(r){let e=RM.decode(r),t=Uint8Array.from(Ti.default.encode(e.length));return he([t,e],t.length+e.length)}function CM(r){let e=Ti.default.decode(r),t=r.slice(Ti.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return"u"+B(t,"base64url")}function PM(r){let e=Ti.default.decode(r),t=r.slice(Ti.default.decode.bytes);if(t.length!==e)throw new Error("inconsistent lengths");return B(t,"base58btc")}function kM(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=Yt.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=om(n);return he([t,i],t.length+i.length)}function NM(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=Yt.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=om(n);return he([t,i],t.length+i.length)}function JE(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=B(e,"base32"),i=tv(t);return`${n}:${i}`}var c0;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(c0||(c0={}));function rv(r){for(let e of r.tuples())switch(e[0]){case c0.ip4:case c0.ip6:return a0(e[0],e[1])}return null}var un;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(un||(un={}));var u0=class extends Ue{constructor(e,t={}){super(),this.multicodecs=[t3,e3],this.peers=new Set,this.streamsInbound=new Map,this.streamsOutbound=new Map,this.outboundInflightQueue=tt({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:un.stopped},this.heartbeatTimer=null,this.runHeartbeat=()=>{let i=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(s=>{this.log("Error running heartbeat",s)}).finally(()=>{if(i?.(),this.status.code===un.started){clearTimeout(this.status.heartbeatTimeout);let s=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;s<this.opts.heartbeatInterval*.25&&(s+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,s)}})};let n={fallbackToFloodsub:!0,floodPublish:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...t,scoreParams:EE(t.scoreParams),scoreThresholds:xE(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??qE,this.globalSignaturePolicy=n.globalSignaturePolicy??Fo,n.fallbackToFloodsub&&this.multicodecs.push(J2),this.log=D(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(i=>i.id.toString())),this.seenCache=new Ja({validityMs:n.seenTTL}),this.publishedMessageIds=new Ja({validityMs:n.seenTTL}),t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Fo:this.msgIdFn=ME;break;case ja:this.msgIdFn=UE;break}if(t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ja({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Q9,this.mcache=t.messageCache||new mf(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(o=>o.meshMessageDeliveriesWindow),1e3),s=DE(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:i/1e3});s.mcacheSize.addCollect(()=>this.onScrapeMetrics(s));for(let o of this.multicodecs)s.protocolsEnabled.set({protocol:o},1);this.metrics=s}else this.metrics=null;this.gossipTracer=new r0(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new t0(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===un.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await em(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=tt({objectMode:!0}),be(this.outboundInflightQueue,async s=>{for await(let{peerId:o,connection:a}of s)await this.createOutboundStream(o,a)}).catch(s=>this.log.error("outbound inflight queue error",s)),await Promise.all(this.opts.directPeers.map(async s=>{await this.components.peerStore.merge(s.id,{multiaddrs:s.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(s=>e.handle(s,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})));let t=Es({onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this)}),n=await Promise.all(this.multicodecs.map(s=>e.register(s,t))),i=setTimeout(this.runHeartbeat,100);this.status={code:un.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 s=>await this.connect(s)))}).catch(s=>{this.log(s)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==un.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:un.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){this.metrics?.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){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let i=new n0(await t.newStream(this.multicodecs),o=>this.log.error("outbound pipe error",o),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,i);let s=i.protocol;s===J2&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(i){this.log.error("createOutboundStream error",i)}}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 s=new i0(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,s),this.pipePeerReadStream(e,s.source).catch(o=>this.log(o))}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 s=rv(n);s!==null?this.score.addIP(i,s):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){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&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close(),i?.close(),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let s of this.topics.values())s.delete(t);for(let[s,o]of this.mesh)o.delete(t)===!0&&this.metrics?.onRemoveFromMesh(s,Ko.Dc,1);for(let s of this.fanout.values())s.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===un.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){try{await be(t,async n=>{for await(let i of n)try{let s=i.subarray(),o=VE(s,this.decodeRpcLimits);if(this.metrics?.onRpcRecv(o,s.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(s){this.metrics?.onRpcDataError(),this.log(s)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions?t.subscriptions.length:0,i=t.messages?t.messages.length:0,s=0,o=0,a=0,c=0;if(t.control&&(t.control.ihave&&(s=t.control.ihave.length),t.control.iwant&&(o=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 ${s} iwant ${o} graft ${a} prune ${c}`),t.subscriptions&&t.subscriptions.length>0){let u=[];t.subscriptions.forEach(l=>{let h=l.topic,f=l.subscribe===!0;if(h!=null){if(this.allowedTopics&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,f),u.push({topic:h,subscribe:f})}}),this.dispatchEvent(new Je("subscription-change",{detail:{peerId:e,subscriptions:u}}))}if(t.messages)for(let u of t.messages){if(this.allowedTopics&&!this.allowedTopics.has(u.topic))continue;let l=this.handleReceivedMessage(e,u).catch(h=>{this.metrics?.onMsgRecvError(u.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await l}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){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);switch(this.metrics?.onMsgRecvResult(t.topic,n.code),n.code){case Pn.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 Pn.invalid:if(n.msgIdStr){let i=n.msgIdStr;this.score.rejectMessage(e.toString(),i,t.topic,n.reason),this.gossipTracer.rejectMessage(i,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case Pn.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 Je("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new Je("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString())}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),i=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(i)return{code:Pn.duplicate,msgIdStr:i};let s=await OE(this.globalSignaturePolicy,t);if(!s.valid)return{code:Pn.invalid,reason:Nr.Error,error:s.error};let o=s.message;try{this.dataTransform&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:Pn.invalid,reason:Nr.Error,error:xr.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Pn.duplicate,msgIdStr:c};this.seenCache.put(c);let l=this.topicValidators.get(t.topic);if(l!=null){let h;try{h=await l(e,o)}catch(f){let d=f.code;d===Y9&&(h=ei.Ignore),d===W9?h=ei.Reject:h=ei.Ignore}if(h!==ei.Accept)return{code:Pn.invalid,reason:J3(h),msgIdStr:c}}return{code:Pn.valid,messageId:u,msg:o}}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){if(t===void 0)return;let n=t.ihave?this.handleIHave(e,t.ihave):[],i=t.iwant?this.handleIWant(e,t.iwant):[],s=t.graft?await this.handleGraft(e,t.graft):[];if(t.prune&&await this.handlePrune(e,t.prune),!n.length&&!i.length&&!s.length)return;let o=this.sendRpc(e,{messages:i,control:{iwant:n,prune:s}}),a=n[0]?.messageIDs;a&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.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){if(!t.length)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:rc.LowScore}),[];let i=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,i),i>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:rc.MaxIhave}),[];let s=this.iasked.get(e)??0;if(s>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:rc.MaxIasked}),[];let o=new Map;if(t.forEach(({topicID:u,messageIDs:l})=>{if(!u||!l||!this.mesh.has(u))return;let h=0;l.forEach(f=>{let d=this.msgIdToStrFn(f);this.seenCache.has(d)||(o.set(d,f),h++)}),this.metrics?.onIhaveRcv(u,l.length,h)}),!o.size)return[];let a=o.size;a+s>5e3&&(a=5e3-s),this.log("IHAVE: Asking for %d out of %d messages from %s",a,o.size,e);let c=Array.from(o.values());return wi(c),c=c.slice(0,a),this.iasked.set(e,s+a),[{messageIDs:c}]}handleIWant(e,t){if(!t.length)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];let i=new Map,s=new Map,o=0;return t.forEach(({messageIDs:a})=>{a&&a.forEach(c=>{let u=this.msgIdToStrFn(c),l=this.mcache.getWithIWantCount(u,e);if(l==null){o++;return}if(s.set(l.msg.topic,1+(s.get(l.msg.topic)??0)),l.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}i.set(u,l.msg)})}),this.metrics?.onIwantRcv(s,o),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),s=Date.now(),o=this.opts.doPX;return t.forEach(({topicID:a})=>{if(!a)return;let c=this.mesh.get(a);if(!c){o=!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),o=!1;return}let u=this.backoff.get(a)?.get(e);if(typeof u=="number"&&s<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,tc.GraftBackoff),o=!1;let l=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;s<l&&this.score.addPenalty(e,1,tc.GraftBackoff),this.addBackoff(e,a),n.push(a);return}if(i<0){this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,i,a),n.push(a),o=!1,this.addBackoff(e,a);return}if(c.size>=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),this.metrics?.onAddToMesh(a,es.Subscribed,1)}),n.length?await Promise.all(n.map(a=>this.makePrune(e,a,o))):[]}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:i,backoff:s,peers:o}of t){if(i==null)continue;let a=this.mesh.get(i);if(!a)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,i),this.score.prune(e,i),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(i,Ko.Unsub,1)),typeof s=="number"&&s>0?this.doAddBackoff(e,i,s*1e3):this.addBackoff(e,i),o&&o.length){if(n<this.opts.scoreThresholds.acceptPXThreshold){this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,i);continue}await this.pxConnect(o)}}}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let i=this.backoff.get(t);i||(i=new Map,this.backoff.set(t,i));let s=Date.now()+n;(i.get(e)??0)<s&&i.set(e,s)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,tc.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((i,s)=>{i<e&&t.delete(s)}),t.size===0&&this.backoff.delete(n)})}async directConnect(){let e=[];this.direct.forEach(t=>{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&&(wi(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(!n.peerID)return;let i=It(n.peerID),s=i.toString();if(!this.peers.has(s)){if(!n.signedPeerRecord){t.push(s);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,i)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(s)}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 s of this.components.registrar.getTopologies(i))s.onConnect(t,n)}subscribe(e){if(this.status.code!==un.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!==un.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){if(this.status.code!==un.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.fanout.get(e);if(n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&t.add(i)}),this.metrics?.onAddToMesh(e,es.Fanout,t.size)),t.size<this.opts.D){let i=t.size;this.getRandomGossipPeers(e,this.opts.D,o=>!t.has(o)&&!this.direct.has(o)&&this.score.score(o)>=0).forEach(o=>{t.add(o)}),this.metrics?.onAddToMesh(e,es.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,e)})}leave(e){if(this.status.code!==un.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t&&(Promise.all(Array.from(t).map(async n=>(this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)))).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let i=new Set,s=this.topics.get(e);s&&(this.direct.forEach(a=>{s.has(a)&&t!==a&&!n?.has(a)&&i.add(a)}),this.floodsubPeers.forEach(a=>{s.has(a)&&t!==a&&!n?.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&i.add(a)}));let o=this.mesh.get(e);return o&&o.size>0&&o.forEach(a=>{t!==a&&!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(s=>{this.direct.has(s)?(t.add(s),n.direct++):this.score.score(s)>=this.opts.scoreThresholds.publishThreshold&&(t.add(s),n.floodsub++)});else{this.direct.forEach(o=>{i.has(o)&&(t.add(o),n.direct++)}),this.floodsubPeers.forEach(o=>{i.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});let s=this.mesh.get(e);if(s&&s.size>0)s.forEach(o=>{t.add(o),n.mesh++});else{let o=this.fanout.get(e);if(o&&o.size>0)o.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){n&&this.score.deliverMessage(n,e,t.topic);let s=this.selectPeersToForward(t.topic,n,i);s.forEach(o=>{this.sendRpc(o,{messages:[t]})}),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,n){let i=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:s,msg:o}=await LE(this.publishConfig,e,t,i),a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),u=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:l,tosendCount:h}=this.selectPeersToPublish(e),f=this.opts.emitSelf===!0&&this.subscriptions.has(e),d=n?.allowPublishToZeroPeers??this.opts.allowPublishToZeroPeers;if(l.size===0&&!d&&!f)throw Error("PublishError.InsufficientPeers");this.seenCache.put(c),this.mcache.put({msgId:a,msgIdStr:c},s,!0),this.publishedMessageIds.put(c);for(let p of l)this.sendRpc(p,{messages:[s]})||l.delete(p);return this.metrics?.onPublishMsg(e,h,l.size,s.data!=null?s.data.length:0),f&&(l.add(this.components.peerId.toString()),super.dispatchEvent(new Je("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:o}})),super.dispatchEvent(new Je("message",{detail:o}))),{recipients:Array.from(l.values()).map(p=>oe(p))}}reportMessageValidationResult(e,t,n){if(n===ei.Accept){let i=this.mcache.validate(e);if(this.metrics?.onReportValidationMcacheHit(i!==null),i!=null){let{message:s,originatingPeers:o}=i;this.score.deliverMessage(t.toString(),e,s.topic),this.forwardMessage(e,i.message,t.toString(),o),this.metrics?.onReportValidation(s.topic,n)}}else{let i=this.mcache.remove(e);if(this.metrics?.onReportValidationMcacheHit(i!==null),i){let s=J3(n),{message:o,originatingPeers:a}=i;this.score.rejectMessage(t.toString(),e,o.topic,s);for(let c of a)this.score.rejectMessage(c,e,o.topic,s);this.metrics?.onReportValidation(o.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){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 s=this.gossip.get(e);s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));let o=Mu.encode(t).finish();try{n.push(o)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),i&&this.control.set(e,i),s&&this.gossip.set(e,s),!1}return this.metrics?.onRpcSent(t,o.length),!0}piggybackControl(e,t,n){if(n.graft){t.control||(t.control={}),t.control.graft||(t.control.graft=[]);for(let i of n.graft)i.topicID&&this.mesh.get(i.topicID)?.has(e)&&t.control.graft.push(i)}if(n.prune){t.control||(t.control={}),t.control.prune||(t.control.prune=[]);for(let i of n.prune)i.topicID&&!this.mesh.get(i.topicID)?.has(e)&&t.control.prune.push(i)}}piggybackGossip(e,t,n){t.control||(t.control={}),t.control.ihave=n}async sendGraftPrune(e,t,n){let i=this.opts.doPX;for(let[s,o]of e){let a=o.map(l=>({topicID:l})),c=[],u=t.get(s);u&&(c=await Promise.all(u.map(async l=>await this.makePrune(s,l,i&&!(n.get(s)??!1)))),t.delete(s)),this.sendRpc(s,{control:{graft:a,prune:c}})}for(let[s,o]of t){let a=await Promise.all(o.map(async c=>await this.makePrune(s,c,i&&!(n.get(s)??!1))));this.sendRpc(s,{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||(wi(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,s=.25*t.size,o=t;s>i&&(i=s),i>o.size?i=o.size:o=wi(Array.from(o)).slice(0,i),o.forEach(a=>{let c=n;n.length>5e3&&(c=wi(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===e3)return{topicID:t,peers:[]};let i=this.opts.pruneBackoff/1e3;if(!n)return{topicID:t,peers:[],backoff:i};let s=this.getRandomGossipPeers(t,this.opts.prunePeers,a=>a!==e&&this.score.score(a)>=0),o=await Promise.all(Array.from(s).map(async a=>{let c=oe(a),u;try{u=await this.components.peerStore.get(c)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}return{peerID:c.toBytes(),signedPeerRecord:u?.peerRecordEnvelope}}));return{topicID:t,peers:o,backoff:i}}async heartbeat(){let{D:e,Dlo:t,Dhi:n,Dscore:i,Dout:s,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,c=p=>{let m=a.get(p);return m===void 0&&(m=this.score.score(p),a.set(p,m)),m},u=new Map,l=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let f=new Map;this.mesh.forEach((p,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(f.set(m,b),g){let v=wi(Array.from(g)),_=this.backoff.get(m);for(let I of v){let P=this.streamsOutbound.get(I);if(P&&this.multicodecs.includes(P.protocol)&&!p.has(I)&&!this.direct.has(I)){let M=c(I);(!_||!_.has(I))&&M>=0&&y.add(I),M>=this.opts.scoreThresholds.gossipThreshold&&b.add(I)}}}let E=(v,_)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",v,m),this.addBackoff(v,m),p.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&b.add(v),this.metrics?.onRemoveFromMesh(m,_,1);let I=l.get(v);I?I.push(m):l.set(v,[m])},R=(v,_)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",v,m),this.score.graft(v,m),p.add(v),b.delete(v),this.metrics?.onAddToMesh(m,_,1);let I=u.get(v);I?I.push(m):u.set(v,[m])};if(p.forEach(v=>{let _=c(v);_<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,_,m),E(v,Ko.BadScore),h.set(v,!0))}),p.size<t){let v=e-p.size;IE(y,v).forEach(I=>{R(I,es.NotEnough)})}if(p.size>n){let v=Array.from(p);v.sort((I,P)=>c(P)-c(I)),v=v.slice(0,i).concat(wi(v.slice(i)));let _=0;if(v.slice(0,e).forEach(I=>{this.outbound.get(I)&&_++}),_<s){let I=M=>{let W=v[M];for(let ue=M;ue>0;ue--)v[ue]=v[ue-1];v[0]=W};if(_>0){let M=_;for(let W=1;W<e&&M>0;W++)this.outbound.get(v[W])&&(I(W),M--)}let P=e-_;for(let M=e;M<v.length&&P>0;M++)this.outbound.get(v[M])&&(I(M),P--)}v.slice(e).forEach(I=>{E(I,Ko.Excess)})}if(p.size>=t){let v=0;if(p.forEach(_=>{this.outbound.get(_)&&v++}),v<s){let _=s-v;e0(y,_,P=>this.outbound.get(P)===!0).forEach(P=>{R(P,es.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&p.size>1){let v=Array.from(p).sort((P,M)=>c(P)-c(M)),_=Math.floor(p.size/2),I=c(v[_]);if(I<this.opts.scoreThresholds.opportunisticGraftThreshold){let P=this.opts.opportunisticGraftPeers,M=e0(y,P,W=>c(W)>I);for(let W of M)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",W,m),R(W,es.Opportunistic)}}});let d=Date.now();this.fanoutLastpub.forEach((p,m)=>{p+o<d&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((p,m)=>{let g=this.topics.get(m);p.forEach(R=>{(!g.has(R)||c(R)<this.opts.scoreThresholds.publishThreshold)&&p.delete(R)});let y=this.topics.get(m),b=[],E=new Set;if(f.set(m,E),y){let R=wi(Array.from(y));for(let v of R){let _=this.streamsOutbound.get(v);if(_&&this.multicodecs.includes(_.protocol)&&!p.has(v)&&!this.direct.has(v)){let I=c(v);I>=this.opts.scoreThresholds.publishThreshold&&b.push(v),I>=this.opts.scoreThresholds.gossipThreshold&&E.add(v)}}}if(p.size<e){let R=e-p.size;b.slice(0,R).forEach(v=>{p.add(v),E?.delete(v)})}}),this.emitGossip(f),await this.sendGraftPrune(u,l,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new Je("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let i=this.topics.get(e);if(!i)return new Set;let s=[];return i.forEach(o=>{let a=this.streamsOutbound.get(o);a&&this.multicodecs.includes(a.protocol)&&n(o)&&s.push(o)}),s=wi(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0;for(let o of this.backoff.values())t+=o.size;e.cacheSize.set({cache:"backoff"},t);for(let[o,a]of this.topics)e.topicPeersCount.set({topicStr:o},a.size);for(let[o,a]of this.mesh)e.meshPeerCounts.set({topicStr:o},a.size);let n=[],i=new Map;e.behaviourPenalty.reset();for(let o of this.peers.keys()){let a=this.score.score(o);n.push(a),i.set(o,a),e.behaviourPenalty.observe(this.score.peerStats.get(o)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let s=FE(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(s)}};u0.multicodec=t3;function iv(r={}){return e=>new u0(e,r)}function am(){let r=Me(),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 l0(){let r=am(),e=am();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}var h0=F(ps(),1),sv=r=>ct.decode(r);sv.bytes=0;function _r(r,e){let t=tt();r.sink(t).catch(o=>{t.end(o)}),r.sink=async o=>{for await(let a of o)t.push(a);t.end()};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 j,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new j:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,h0.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new j,c=e?.lengthDecoder??sv;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,h0.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,h0.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?t.push(o):t.push(o.subarray())},writeLP:o=>{s.write(Et.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=r.source;return r.source=async function*(){yield*i,yield*o}(),r}};return s}var ov=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function cm(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function aU(r){if(typeof r!="boolean")throw new Error(`Expected boolean, not ${r}`)}function av(r,...e){if(!(r instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new TypeError(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function cU(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");cm(r.outputLen),cm(r.blockLen)}function uU(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function lU(r,e){av(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var hU={number:cm,bool:aU,bytes:av,hash:cU,exists:uU,output:lU},ln=hU;var fU=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var f0=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ti=(r,e)=>r<<32-e|r>>>e,dU=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!dU)throw new Error("Non little-endian hardware is not supported");var Xse=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function pU(r){if(typeof r!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof r}`);return new TextEncoder().encode(r)}function $s(r){if(typeof r=="string"&&(r=pU(r)),!(r instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof r})`);return r}var oc=class{clone(){return this._cloneInto()}};function um(r){let e=n=>r().update($s(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}var d0=class extends oc{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ln.hash(e);let n=$s(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return ln.exists(this),this.iHash.update(e),this}digestInto(e){ln.exists(this),ln.bytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},p0=(r,e,t)=>new d0(r,e).update(t).digest();p0.create=(r,e)=>new d0(r,e);function mU(r,e,t){return ln.hash(r),t===void 0&&(t=new Uint8Array(r.outputLen)),p0(r,$s(t),$s(e))}var lm=new Uint8Array([0]),cv=new Uint8Array;function gU(r,e,t,n=32){if(ln.hash(r),ln.number(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let i=Math.ceil(n/r.outputLen);t===void 0&&(t=cv);let s=new Uint8Array(i*r.outputLen),o=p0.create(r,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)lm[0]=u+1,a.update(u===0?cv:c).update(t).update(lm).digestInto(c),s.set(c,r.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),lm.fill(0),s.slice(0,n)}var uv=(r,e,t,n,i)=>gU(r,mU(r,e,t),n,i);function yU(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+u,a,n)}var m0=class extends oc{constructor(e,t,n,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=f0(this.buffer)}update(e){ln.exists(this);let{view:t,buffer:n,blockLen:i}=this;e=$s(e);let s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=f0(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ln.exists(this),ln.output(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)t[h]=0;yU(n,i-8,BigInt(this.length*8),s),this.process(n,0);let a=f0(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%t&&e.buffer.set(n),e}};var wU=(r,e,t)=>r&e^~r&t,bU=(r,e,t)=>r&e^r&t^e&t,EU=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Gs=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ws=new Uint32Array(64),g0=class extends m0{constructor(){super(64,32,8,!1),this.A=Gs[0]|0,this.B=Gs[1]|0,this.C=Gs[2]|0,this.D=Gs[3]|0,this.E=Gs[4]|0,this.F=Gs[5]|0,this.G=Gs[6]|0,this.H=Gs[7]|0}get(){let{A:e,B:t,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,t,n,i,s,o,a,c]}set(e,t,n,i,s,o,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Ws[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let f=Ws[h-15],d=Ws[h-2],p=ti(f,7)^ti(f,18)^f>>>3,m=ti(d,17)^ti(d,19)^d>>>10;Ws[h]=m+Ws[h-7]+p+Ws[h-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let f=ti(a,6)^ti(a,11)^ti(a,25),d=l+f+wU(a,c,u)+EU[h]+Ws[h]|0,m=(ti(n,2)^ti(n,13)^ti(n,22))+bU(n,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=n,n=d+m|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){Ws.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},hm=class extends g0{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}},fm=um(()=>new g0),loe=um(()=>new hm);var Rm=F(ul(),1),cc=F(Am(),1),Im={hashSHA256(r){return fm(r)},getHKDF(r,e){let t=uv(fm,e,r,void 0,96),n=t.subarray(0,32),i=t.subarray(32,64),s=t.subarray(64,96);return[n,i,s]},generateX25519KeyPair(){let r=cc.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=cc.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return cc.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new Rm.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new Rm.ChaCha20Poly1305(n).open(e,r,t,i)}};var Tm=F(ul(),1);var xF=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),uc=r=>{let e=xF(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};uc.bytes=2;var fl=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)};fl.bytes=2;function Lv(r){return he([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function Ov(r){return he([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function Bv(r){return he([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function Mv(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 Uv(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 Fv(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 qv(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield uc(o.byteLength),yield o}}}function Vv(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-Tm.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-Tm.TAG_LENGTH),{plaintext:c,valid:u}=r.decrypt(o,r.session,a);if(!u)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var Dm=class extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=Dm.code}},lc=Dm;br(lc,"code","ERR_UNEXPECTED_PEER");var Cm=class extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Cm.code}},Ys=Cm;br(Ys,"code","ERR_INVALID_CRYPTO_EXCHANGE");var T0;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(T0||(T0={}));var pl;(function(r){let e;r.codec=()=>(e==null&&(e=se((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),T0.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=T0.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(pl||(pl={}));async function zv(r,e,t){let n=await SF(r,Hv(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return _F(r.publicKey,n,t)}function _F(r,e,t){return pl.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function SF(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await cn(r.privateKey)).sign(e)}async function Pm(r){return er(r.identityKey)}function km(r){return pl.decode(r)}function Hv(r){let e=q("noise-libp2p-static-key:");return he([e,r],e.length+r.length)}async function Nm(r,e,t){let n=await er(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=Hv(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 kr(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function ml(r){return!(!(r instanceof Uint8Array)||r.length!==32)}function D0(r,e){for(let t=0;t<r.byteLength;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return r.byteLength>e.byteLength?1:r.byteLength<e.byteLength?-1:0}function is(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=Tr(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return qi(t)}var or=D("libp2p:noise");var kn;ov?kn=or:kn=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function $v(r){kn(`LOCAL_STATIC_PUBLIC_KEY ${B(r.publicKey,"hex")}`),kn(`LOCAL_STATIC_PRIVATE_KEY ${B(r.privateKey,"hex")}`)}function Lm(r){r?(kn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${B(r.publicKey,"hex")}`),kn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${B(r.privateKey,"hex")}`)):kn("Missing local ephemeral keys.")}function Gv(r){kn(`REMOTE_STATIC_PUBLIC_KEY ${B(r,"hex")}`)}function Om(r){kn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${B(r,"hex")}`)}function Wv(r){r.cs1&&r.cs2?(kn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${B(r.cs1.k,"hex")}`),kn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${B(r.cs2.k,"hex")}`)):kn("Missing cipher state.")}var AF="Cipherstate has reached maximum n, a new handshake must be performed",C0=class{n;bytes;view;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(AF)}};var P0=class{crypto;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:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return pe(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,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,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 or.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(he([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 C0}}initializeSymmetric(e){let t=q(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),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),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var k0=class extends P0{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,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 s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}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,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}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 s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return ml(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(ml(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&&ml(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&ml(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:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,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:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,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:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var N0=class{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;constructor(e,t,n,i,s,o,a,c){this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new k0(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if($v(this.session.hs.s),this.isInitiator){or.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(Lv(e)),or.trace("Stage 0 - Initiator finished sending first message."),Lm(this.session.hs.e)}else{or.trace("Stage 0 - Responder waiting to receive first message...");let e=Mv((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new Ys("xx handshake stage 0 validation fail");or.trace("Stage 0 - Responder received first message."),Om(this.session.hs.re)}}async exchange(){if(this.isInitiator){or.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=Uv((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Ys("xx handshake stage 1 validation fail");or.trace("Stage 1 - Initiator received the message."),Om(this.session.hs.re),Gv(this.session.hs.rs),or.trace("Initiator going to check remote's signature...");try{let i=km(t);this.remotePeer=this.remotePeer||await Pm(i),await Nm(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new lc(`Error occurred while verifying signed payload: ${s.message}`)}or.trace("All good with the signature!")}else{or.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(Ov(e)),or.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lm(this.session.hs.e)}}async finish(){if(this.isInitiator){or.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(Bv(e)),or.trace("Stage 2 - Initiator sent message with signed payload.")}else{or.trace("Stage 2 - Responder waiting for third handshake message...");let e=Fv((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Ys("xx handshake stage 2 validation fail");or.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=km(t);this.remotePeer=this.remotePeer||await Pm(i),await Nm(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new lc(`Error occurred while verifying signed payload: ${s.message}`)}}Wv(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 Ys("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 Yv(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 L0=class{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;constructor(e={}){let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??Im,this.extensions=n,this.metrics=o?Yv(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=_r(t,{lengthEncoder:uc,lengthDecoder:fl,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=_r(t,{lengthEncoder:uc,lengthDecoder:fl,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await zv(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new N0(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=l0(),s=e.unwrap();return await be(n,qv(t,this.metrics),s,o=>Ct(o,{lengthDecoder:fl}),Vv(t,this.metrics),n),i}};function O0(r={}){return()=>new L0(r)}var hc="ERR_INVALID_FRAME",Bm="ERR_UNREQUESTED_PING",Mm="ERR_NOT_MATCHING_PING",Um="ERR_STREAM_ALREADY_EXISTS",Fm="ERR_DECODE_INVALID_VERSION",Km="ERR_BOTH_CLIENTS",qm="ERR_RECV_WINDOW_EXCEEDED",Qv=new Set([hc,Bm,Mm,Um,Fm,Km,qm]),Qs="ERR_INVALID_CONFIG",B0="ERR_MUXER_LOCAL_CLOSED",Vm="ERR_MUXER_REMOTE_CLOSED",Xv="ERR_STREAM_RESET",gl="ERR_STREAM_ABORT",jv="ERROR_MAX_OUTBOUND_STREAMS_EXCEEDED",Zv="ERR_DECODE_IN_PROGRESS",yl=256*1024,Jv=16*1024*1024;var ex={log:D("libp2p:yamux"),enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:yl,maxStreamWindowSize:Jv,maxMessageSize:64*1024};function tx(r){if(r.keepAliveInterval<=0)throw new w("keep-alive interval must be positive",Qs);if(r.maxInboundStreams<0)throw new w("max inbound streams must be larger or equal 0",Qs);if(r.maxOutboundStreams<0)throw new w("max outbound streams must be larger or equal 0",Qs);if(r.initialStreamWindowSize<yl)throw new w("InitialStreamWindowSize must be larger or equal 256 kB",Qs);if(r.maxStreamWindowSize<r.initialStreamWindowSize)throw new w("MaxStreamWindowSize must be larger than the InitialStreamWindowSize",Qs);if(r.maxStreamWindowSize>2**32-1)throw new w("MaxStreamWindowSize must be less than equal MAX_UINT32",Qs);if(r.maxMessageSize<1024)throw new w("MaxMessageSize must be greater than a kilobyte",Qs)}var Tt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Tt||(Tt={}));var wt;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(wt||(wt={}));var RF=Object.values(wt).filter(r=>typeof r!="string"),rx=0,Hr;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Hr||(Hr={}));var Xs=12;function zm(r){let e=RF.filter(t=>(r.flag&t)===t).map(t=>wt[t]).join("|");return`streamID=${r.streamID} type=${Tt[r.type]} flag=${e} length=${r.length}`}var nx=2**24;function IF(r){if(r[0]!==rx)throw new w("Invalid frame version",Fm);return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*nx+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*nx+(r[9]<<16)+(r[10]<<8)+r[11]}}var M0=class{source;buffer;frameInProgress;constructor(e){this.source=TF(e),this.buffer=new j,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let t=this.readHeader();if(t===void 0)break;let{type:n,length:i}=t;n===Tt.Data?(this.frameInProgress=!0,yield{header:t,readData:this.readBytes.bind(this,i)}):yield{header:t}}}readHeader(){if(this.frameInProgress)throw new w("decoding frame already in progress",Zv);if(this.buffer.length<Xs)return;let e=IF(this.buffer.subarray(0,Xs));return this.buffer.consume(Xs),e}async readBytes(e){if(this.buffer.length<e){for await(let n of this.source)if(this.buffer.append(n),this.buffer.length>=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function TF(r){if(r[Symbol.iterator]!==void 0){let e=r[Symbol.iterator]();return e.return=void 0,{[Symbol.iterator](){return e}}}else if(r[Symbol.asyncIterator]!==void 0){let e=r[Symbol.asyncIterator]();return e.return=void 0,{[Symbol.asyncIterator](){return e}}}else throw new Error("a source must be either an iterable or an async iterable")}function Hm(r){let e=new Uint8Array(Xs);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var qt;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished"})(qt||(qt={}));var Or;(function(r){r[r.Open=0]="Open",r[r.Closed=1]="Closed",r[r.Reset=2]="Reset"})(Or||(Or={}));var U0=class{id;name;stat;metadata;state;readState;writeState;sourceInput;source;sink;config;log;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;abortController;sendFrame;onStreamEnd;constructor(e){this.config=e.config,this.log=e.log,this._id=e.id,this.id=String(e.id),this.name=e.name,this.stat={direction:e.direction,timeline:{open:Date.now()}},this.metadata={},this.state=e.state,this.readState=Or.Open,this.writeState=Or.Open,this.sendWindowCapacity=yl,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.abortController=new AbortController,this.sendFrame=e.sendFrame,this.onStreamEnd=e.onStreamEnd,this.sourceInput=tt({onEnd:t=>{t!=null?this.log?.error("stream source ended id=%s",this._id,t):this.log?.trace("stream source ended id=%s",this._id),this.closeRead()}}),this.source=this.createSource(),this.sink=async t=>{if(this.writeState!==Or.Open)throw new Error("stream closed for writing");t=lt(t,this.abortController.signal,{returnOnAbort:!0});try{for await(let n of t)for(;n.length!==0;){this.sendWindowCapacity===0&&await this.waitForSendWindowCapacity();let i=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-Xs,n.length);this.sendData(n.subarray(0,i)),this.sendWindowCapacity-=i,n=n.subarray(i)}}catch(n){this.log?.error("stream sink error id=%s",this._id,n)}finally{this.log?.trace("stream sink ended id=%s",this._id),this.closeWrite()}}}async*createSource(){try{for await(let e of this.sourceInput)this.sendWindowUpdate(),yield e}catch(e){if(e.code!==gl)throw this.log?.error("stream source error id=%s",this._id,e),e}}close(){this.log?.trace("stream close id=%s",this._id),this.closeRead(),this.closeWrite()}closeRead(){this.state!==qt.Finished&&this.readState===Or.Open&&(this.log?.trace("stream close read id=%s",this._id),this.readState=Or.Closed,this.sourceInput.end(),this.writeState!==Or.Open&&this.finish())}closeWrite(){this.state!==qt.Finished&&this.writeState===Or.Open&&(this.log?.trace("stream close write id=%s",this._id),this.writeState=Or.Closed,this.sendClose(),this.abortController.abort(),this.readState!==Or.Open&&this.finish())}abort(e){switch(this.state){case qt.Finished:return;case qt.Init:break;case qt.SYNSent:case qt.SYNReceived:case qt.Established:this.sendReset();break;default:throw new Error("unreachable")}e!=null?this.log?.error("stream abort id=%s error=%s",this._id,e):this.log?.trace("stream abort id=%s",this._id),this.onReset(new w(String(e)??"stream aborted",gl))}reset(){this.state!==qt.Finished&&(this.log?.trace("stream reset id=%s",this._id),this.onReset(new w("stream reset",Xv)))}onReset(e){this.writeState===Or.Open&&(this.writeState=Or.Reset),this.readState===Or.Open&&(this.readState=Or.Reset),this.state=qt.Finished,this.sourceInput.end(e),this.abortController.abort(),this.finish()}async waitForSendWindowCapacity(){if(this.abortController.signal.aborted)throw new w("stream aborted",gl);if(this.sendWindowCapacity>0)return;let e,t=()=>{e(new w("stream aborted",gl))};this.abortController.signal.addEventListener("abort",t),await new Promise((n,i)=>{this.sendWindowCapacityUpdate=()=>{this.abortController.signal.removeEventListener("abort",t),n(void 0)},e=i})}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new w("receive window exceeded",qm,{available:this.recvWindowCapacity,recv:e.length});let n=await t();this.recvWindowCapacity-=e.length,this.sourceInput.push(n)}processFlags(e){(e&wt.ACK)===wt.ACK&&this.state===qt.SYNSent&&(this.state=qt.Established),(e&wt.FIN)===wt.FIN&&this.closeRead(),(e&wt.RST)===wt.RST&&this.reset()}finish(){this.log?.trace("stream finished id=%s",this._id),this.state=qt.Finished,this.stat.timeline.close=Date.now(),this.onStreamEnd()}getSendFlags(){switch(this.state){case qt.Init:return this.state=qt.SYNSent,wt.SYN;case qt.SYNReceived:return this.state=qt.Established,wt.ACK;default:return 0}}sendWindowUpdate(){let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>0&&t-this.epochStart<n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let i=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Tt.WindowUpdate,flag:e,streamID:this._id,length:i})}sendData(e){let t=this.getSendFlags();this.sendFrame({type:Tt.Data,flag:t,streamID:this._id,length:e.length},e)}sendClose(){let e=this.getSendFlags()|wt.FIN;this.sendFrame({type:Tt.WindowUpdate,flag:e,streamID:this._id,length:0})}sendReset(){this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:this._id,length:0})}};var ix="/yamux/1.0.0",F0=class{protocol=ix;_init;constructor(e={}){this._init=e}createStreamMuxer(e){return new $m({...this._init,...e})}},$m=class{protocol=ix;source;sink;_init;config;log;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e){this._init=e,this.client=e.direction==="outbound",this.config={...ex,...e},this.log=this.config.log,tx(this.config),this.closeController=new AbortController,this.onIncomingStream=e.onIncomingStream,this.onStreamEnd=e.onStreamEnd,this._streams=new Map,this.source=tt({onEnd:t=>{this.log?.trace("muxer source ended"),this.close(t)}}),this.sink=async t=>{let n;this._init.signal!=null&&(n=it([this.closeController.signal,this._init.signal])),t=lt(t,n??this.closeController.signal,{returnOnAbort:!0});let i,s;try{let o=new M0(t);await be(o.emitFrames.bind(o),async a=>{for await(let{header:c,readData:u}of a)await this.handleFrame(c,u)}),i=Hr.NormalTermination}catch(o){let a=o.code;Qv.has(a)?(this.log?.error("protocol error in sink",o),i=Hr.ProtocolError):(this.log?.error("internal error in sink",o),i=Hr.InternalError),s=o}finally{n?.clear()}this.log?.trace("muxer sink ended"),this.close(s,i)},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=0,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch(t=>this.log?.error("keepalive error: %s",t))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new w("muxer closed remotely",Vm);if(this.localGoAway!==void 0)throw new w("muxer closed locally",B0);let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new w("max outbound streams exceeded",jv);this.log?.trace("new outgoing stream id=%s",t);let n=this._newStream(t,e,qt.Init,"outbound");return this._streams.set(t,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}async ping(){if(this.remoteGoAway!==void 0)throw new w("muxer closed remotely",Vm);if(this.localGoAway!==void 0)throw new w("muxer closed locally",B0);if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((i,s)=>{let o=()=>{s(new w("muxer closed locally",B0))};this.closeController.signal.addEventListener("abort",o,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",o),i()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let n=Date.now();this.rtt=n-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}close(e,t){if(!this.closeController.signal.aborted){if(t=t??(e===void 0?Hr.InternalError:Hr.NormalTermination),e!=null?this.log?.error("muxer close reason=%s error=%s",Hr[t],e):this.log?.trace("muxer close reason=%s",Hr[t]),e===void 0)for(let n of this._streams.values())n.close();else for(let n of this._streams.values())n.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,n,i){if(this._streams.get(e)!=null)throw new w("Stream already exists",Um,{id:e});let s=new U0({id:e,name:t,state:n,direction:i,sendFrame:this.sendFrame.bind(this),onStreamEnd:()=>{this.closeStream(e),this.onStreamEnd?.(s)},log:this.log,config:this.config,getRTT:this.getRTT.bind(this)});return s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){let e=new Promise((t,n)=>{this.closeController.signal.addEventListener("abort",n,{once:!0})});for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let t;try{await Promise.race([e,new Promise(n=>{t=setTimeout(n,this.config.keepAliveInterval)})]),this.ping().catch(n=>this.log?.error("ping error: %s",n))}catch{clearInterval(t);return}}}async handleFrame(e,t){let{streamID:n,type:i,length:s}=e;if(this.log?.trace("received frame %s",zm(e)),n===0)switch(i){case Tt.Ping:{this.handlePing(e);return}case Tt.GoAway:{this.handleGoAway(s);return}default:throw new w("Invalid frame type",hc,{header:e})}else switch(e.type){case Tt.Data:case Tt.WindowUpdate:{await this.handleStreamMessage(e,t);return}default:throw new w("Invalid frame type",hc,{header:e})}}handlePing(e){if(e.flag===wt.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,wt.ACK);else if(e.flag===wt.ACK)this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new w("Invalid frame flag",hc,{header:e})}handlePingResponse(e){if(this.activePing===void 0)throw new w("ping not requested",Bm);if(this.activePing.id!==e)throw new w("ping doesn't match our id",Mm);this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",Hr[e]??"unknown"),this.remoteGoAway=e;for(let t of this._streams.values())t.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:n,flag:i,type:s}=e;(i&wt.SYN)===wt.SYN&&this.incomingStream(n);let o=this._streams.get(n);if(o===void 0){if(s===Tt.Data){if(this.log?.("discarding data for stream id=%s",n),t===void 0)throw new Error("unreachable");await t()}else this.log?.("frame for missing stream id=%s",n);return}switch(s){case Tt.WindowUpdate:{o.handleWindowUpdate(e);return}case Tt.Data:{if(t===void 0)throw new Error("unreachable");await o.handleData(e,t);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new w("both endpoints are clients",Km);if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Tt.WindowUpdate,flag:wt.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,qt.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %s",zm(e)),e.type===Tt.Data){if(t===void 0)throw new w("invalid frame",hc);this.source.push(Hm(e)),this.source.push(t)}else this.source.push(Hm(e))}sendPing(e,t=wt.SYN){t===wt.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:Tt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Hr.NormalTermination){this.log?.("sending GoAway reason=%s",Hr[e]),this.localGoAway=e,this.sendFrame({type:Tt.GoAway,flag:0,streamID:0,length:e})}};function sx(r={}){return()=>new F0(r)}var qo=Symbol.for("@libp2p/peer-discovery");var jm=F(bo(),1);var fc=F(bo(),1);function DF(r){let e=[],t=r.split("/").slice(1);if(t.length===1&&t[0]==="")return[];for(let n=0;n<t.length;n++){let i=t[n],s=X(i);if(s.size===0){e.push([i]);continue}if(n++,n>=t.length)throw ax("invalid address: "+r);if(s.path===!0){e.push([i,Xm(t.slice(n).join("/"))]);break}e.push([i,t[n]])}return e}function CF(r){let e=[];return r.map(t=>{let n=V0(t);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Xm(e.join("/"))}function PF(r){return r.map(e=>{Array.isArray(e)||(e=[e]);let t=V0(e);return e.length>1?[t.code,ev(t.code,e[1])]:[t.code]})}function Gm(r){return r.map(e=>{let t=V0(e);return e[1]!=null?[t.code,a0(t.code,e[1])]:[t.code]})}function Wm(r){return q0(he(r.map(e=>{let t=V0(e),n=Uint8Array.from(fc.default.encode(t.code));return e.length>1&&e[1]!=null&&(n=he([n,e[1]])),n})))}function Ym(r,e){return r.size>0?r.size/8:r.size===0?0:fc.default.decode(e)+(fc.default.decode.bytes??0)}function K0(r){let e=[],t=0;for(;t<r.length;){let n=fc.default.decode(r,t),i=fc.default.decode.bytes??0,s=X(n),o=Ym(s,r.slice(t+i));if(o===0){e.push([n]),t+=i;continue}let a=r.slice(t+i,t+i+o);if(t+=o+i,t>r.length)throw ax("Invalid address Uint8Array: "+B(r,"base16"));e.push([n,a])}return e}function Qm(r){let e=K0(r),t=Gm(e);return CF(t)}function kF(r){r=Xm(r);let e=DF(r),t=PF(e);return Wm(t)}function ox(r){return kF(r)}function q0(r){let e=NF(r);if(e!=null)throw e;return Uint8Array.from(r)}function NF(r){try{K0(r)}catch(e){return e}}function Xm(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ax(r){return new Error("Error parsing address: "+r)}function V0(r){return X(r[0])}var OF=Symbol.for("nodejs.util.inspect.custom"),BF=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],Zm=new Map,cx=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Vo(r){return!!r?.[cx]}var ss=class{bytes;#e;#t;#n;#r;[cx]=!0;constructor(e){if(e==null&&(e=""),e instanceof Uint8Array)this.bytes=q0(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=ox(e)}else if(Vo(e))this.bytes=q0(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return this.#e==null&&(this.#e=Qm(this.bytes)),this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,i,s="",o=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),l=X("dns6"),h=X("ip6zone");for(let[d,p]of this.stringTuples())d===h.code&&(s=`%${p??""}`),BF.includes(d)&&(t=o.name,i=443,n=`${p??""}${s}`,e=d===l.code?6:4),(d===o.code||d===a.code)&&(t=X(d).name,i=parseInt(p??"")),(d===c.code||d===u.code)&&(t=X(d).name,n=`${p??""}${s}`,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({},X(e)))}protoCodes(){let e=[],t=this.bytes,n=0;for(;n<t.length;){let i=jm.default.decode(t,n),s=jm.default.decode.bytes??0,o=X(i),a=Ym(o,t.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return this.#t==null&&(this.#t=K0(this.bytes)),this.#t}stringTuples(){return this.#n==null&&(this.#n=Gm(this.tuples())),this.#n}encapsulate(e){return e=new ss(e),new ss(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 ss(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 ss(Wm(t.slice(0,n)));return this}getPeerId(){try{let t=this.stringTuples().filter(n=>n[0]===ol.ipfs.code).pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?B(me.decode(`z${n}`),"base58btc"):B(ee.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(this.#r===void 0)try{this.#r=this.stringTuples().filter(e=>X(e[0]).path===!0)[0][1],this.#r==null&&(this.#r=null)}catch{this.#r=null}return this.#r}equals(e){return pe(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Zm.get(t.name);if(n==null)throw new w(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new ss(s))}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)}[OF](){return`Multiaddr(${Qm(this.bytes)})`}};function re(r){return new ss(r)}var MF=G("dns4"),UF=G("dns6"),FF=G("dnsaddr"),Zs=Qt(G("dns"),FF,MF,UF),z0=Qt(G("ip4"),G("ip6")),dc=Qt(ce(z0,G("tcp")),ce(Zs,G("tcp"))),H0=ce(z0,G("udp")),KF=ce(H0,G("utp")),qF=ce(H0,G("quic")),VF=ce(H0,G("quic-v1")),zo=Qt(ce(dc,G("ws")),ce(Zs,G("ws"))),Js=Qt(ce(dc,G("wss")),ce(Zs,G("wss")),ce(dc,G("tls"),G("ws")),ce(Zs,G("tls"),G("ws"))),Jm=Qt(ce(dc,G("http")),ce(z0,G("http")),ce(Zs,G("http"))),e4=Qt(ce(dc,G("https")),ce(z0,G("https")),ce(Zs,G("https"))),ux=ce(H0,G("webrtc-direct"),G("certhash")),fx=Qt(ce(ux,G("p2p")),ux),lx=ce(VF,G("webtransport"),G("certhash"),G("certhash")),dx=Qt(ce(lx,G("p2p")),lx),px=Qt(ce(zo,G("p2p-webrtc-star"),G("p2p")),ce(Js,G("p2p-webrtc-star"),G("p2p")),ce(zo,G("p2p-webrtc-star")),ce(Js,G("p2p-webrtc-star"))),Oce=Qt(ce(zo,G("p2p-websocket-star"),G("p2p")),ce(Js,G("p2p-websocket-star"),G("p2p")),ce(zo,G("p2p-websocket-star")),ce(Js,G("p2p-websocket-star"))),mx=Qt(ce(Jm,G("p2p-webrtc-direct"),G("p2p")),ce(e4,G("p2p-webrtc-direct"),G("p2p")),ce(Jm,G("p2p-webrtc-direct")),ce(e4,G("p2p-webrtc-direct"))),Ho=Qt(zo,Js,Jm,e4,px,mx,dc,KF,qF,Zs,fx,dx),Bce=Qt(ce(Ho,G("p2p-stardust"),G("p2p")),ce(Ho,G("p2p-stardust"))),js=Qt(ce(Ho,G("p2p")),px,mx,fx,dx,G("p2p")),hx=Qt(ce(js,G("p2p-circuit"),js),ce(js,G("p2p-circuit")),ce(G("p2p-circuit"),js),ce(Ho,G("p2p-circuit")),ce(G("p2p-circuit"),Ho),G("p2p-circuit")),gx=()=>Qt(ce(hx,gx),hx),ri=gx(),yx=Qt(ce(ri,js,ri),ce(js,ri),ce(ri,js),ri,js);var Mce=Qt(ce(ri,G("webrtc"),G("p2p")),ce(ri,G("webrtc")),ce(Ho,G("webrtc"),G("p2p")),ce(Ho,G("webrtc")),G("webrtc"));function wx(r){function e(t){let n;try{n=re(t)}catch{return!1}let i=r(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return e}function ce(...r){function e(t){if(t.length<r.length)return null;let n=t;return r.some(i=>(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:wx(e),partialMatch:e}}function Qt(...r){function e(n){let i=null;return r.some(s=>{let o=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return o!=null?(i=o,!0):!1}),i}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:wx(e),partialMatch:e}}function G(r){let e=r;function t(i){let s;try{s=re(i)}catch{return!1}let o=s.protoNames();return o.length===1&&o[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 $0=D("libp2p:bootstrap"),zF="bootstrap",HF=50,$F=12e4,GF=1e3,G0=class extends Ue{timer;list;timeout;components;_init;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??GF,this.list=[];for(let n of t.list){if(!yx.matches(n)){$0.error("Invalid multiaddr");continue}let i=re(n),s=i.getPeerId();if(s==null){$0.error("Invalid bootstrap multiaddr without peer id");continue}let o={id:oe(s),multiaddrs:[i],protocols:[]};this.list.push(o)}this._init=t}[qo]=this;[Symbol.toStringTag]="@libp2p/bootstrap";isStarted(){return!!this.timer}start(){this.isStarted()||($0("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{$0.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??zF]:{value:this._init.tagValue??HF,ttl:this._init.tagTTL??$F}}}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};br(G0,"tag","bootstrap");function Ex(r){return e=>new G0(e,r)}async function*t4(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()}}var Rx=F(Sx(),1);var Y0=D("ipni-content-routing"),Ax={concurrentRequests:4,timeout:3e4},n4=class{started;httpQueue;shutDownController;clientUrl;timeout;constructor(e,t={}){Y0("enabled IPNI routing via",e),this.started=!1,this.shutDownController=new AbortController,this.httpQueue=new vt({concurrency:t.concurrentRequests??Ax.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Ax.timeout}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*findProviders(e,t={}){Y0("findProviders starts: %c",e);let n=it([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),i=Me(),s=Me();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let o=`${this.clientUrl}cid/${e.toString()}?cascade=ipfs-dht`,c=await fetch(o,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.body==null)throw new w("IPNI response had no body","ERR_BAD_RESPONSE");for await(let u of(0,Rx.default)(t4(c.body)))u.Metadata==="gBI="&&(yield this.mapEvent(u))}catch(o){Y0.error("findProviders errored:",o)}finally{n.clear(),s.resolve(),Y0("findProviders finished: %c",e)}}mapEvent(e){let t=oe(e.Provider.ID),n=[];for(let s of e.Provider.Addrs){let o=re(s);n.push(o)}return{id:t,multiaddrs:n,protocols:[]}}async provide(){}async put(){}async get(){throw new w("Not found","ERR_NOT_FOUND")}};function Ix(r,e={}){return()=>new n4(r,e)}var wl=Symbol.for("@libp2p/content-routing");var bl=Symbol.for("@libp2p/peer-routing");var Lx=F(Tx(),1);var Dx="[a-fA-F\\d:]",eo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Dx})|(?<=${Dx})(?=\\s|$))`:"",ni="(?: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}",$t="[a-fA-F\\d]{1,4}",Q0=`
|
|
53
|
+
(?:
|
|
54
|
+
(?:${$t}:){7}(?:${$t}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
55
|
+
(?:${$t}:){6}(?:${ni}|:${$t}|:)| // 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
|
|
56
|
+
(?:${$t}:){5}(?::${ni}|(?::${$t}){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
|
|
57
|
+
(?:${$t}:){4}(?:(?::${$t}){0,1}:${ni}|(?::${$t}){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
|
|
58
|
+
(?:${$t}:){3}(?:(?::${$t}){0,2}:${ni}|(?::${$t}){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
|
|
59
|
+
(?:${$t}:){2}(?:(?::${$t}){0,3}:${ni}|(?::${$t}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
60
|
+
(?:${$t}:){1}(?:(?::${$t}){0,4}:${ni}|(?::${$t}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
61
|
+
(?::(?:(?::${$t}){0,5}:${ni}|(?::${$t}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
62
|
+
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
63
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),WF=new RegExp(`(?:^${ni}$)|(?:^${Q0}$)`),YF=new RegExp(`^${ni}$`),QF=new RegExp(`^${Q0}$`),i4=r=>r&&r.exact?WF:new RegExp(`(?:${eo(r)}${ni}${eo(r)})|(?:${eo(r)}${Q0}${eo(r)})`,"g");i4.v4=r=>r&&r.exact?YF:new RegExp(`${eo(r)}${ni}${eo(r)}`,"g");i4.v6=r=>r&&r.exact?QF:new RegExp(`${eo(r)}${Q0}${eo(r)}`,"g");var Cx=i4;var Ox=F(kx(),1),{isValid:XF,parse:jF}=Ox.default,ZF=["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"],JF=ZF.map(r=>new Lx.Netmask(r));function eK(r){for(let e of JF)if(e.contains(r))return!0;return!1}function Nx(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 Bx=r=>{if(XF(r)){let e=jF(r);if(e.kind()==="ipv4")return eK(e.toNormalizedString());if(e.kind()==="ipv6")return Nx(r)}else if(ic(r)&&Cx.v6().test(r))return Nx(r)};var Nn=Bx;function Mx(r,e,t){if(t.length===0){let o="No records given";throw new w(o,"ERR_NO_RECORDS_RECEIVED")}let i=B(e).split("/");if(i.length<3){let o="Record key does not have a selector function";throw new w(o,"ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")}let s=r[i[1].toString()];if(s==null){let o=`Unrecognized key prefix: ${i[1]}`;throw new w(o,"ERR_UNRECOGNIZED_KEY_PREFIX")}return t.length===1?0:s(e,t)}function tK(r,e){return 0}var Ux={pk:tK};async function pc(r,e){let t=e.key,i=B(t).split("/");if(i.length<3)return;let s=r[i[1].toString()];if(s==null){let o="Invalid record keytype";throw new w(o,"ERR_INVALID_RECORD_KEY_TYPE")}await s(t,e.value)}var rK=async(r,e)=>{if(!(r instanceof Uint8Array))throw new w('"key" must be a Uint8Array',"ERR_INVALID_RECORD_KEY_NOT_BUFFER");if(r.byteLength<5)throw new w("invalid public key record","ERR_INVALID_RECORD_KEY_TOO_SHORT");if(B(r.subarray(0,4))!=="/pk/")throw new w("key was not prefixed with /pk/","ERR_INVALID_RECORD_KEY_BAD_PREFIX");let n=r.slice(4),i=await Pe.digest(e);if(!pe(n,i.bytes))throw new w("public key does not match passed in key","ERR_INVALID_RECORD_HASH_MISMATCH")},Fx={pk:rK};var Kx="/lan",qx="/ipfs",Vx="/kad/1.0.0",zx="/dht/record",s4="/dht/provider";var vl;(function(r){let e;r.codec=()=>(e==null&&(e=se((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:""},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>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(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(vl||(vl={}));function Hx(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"),s=String(r.getUTCMinutes()).padStart(2,"0"),o=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${i}:${s}:${o}.${c}Z`}function $x(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,s=parseInt(t[3],10),o=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,s,o,a,c,u))}var Gt=class{constructor(e,t,n){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 vl.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:Hx(this.timeReceived)}}static deserialize(e){let t=vl.decode(e);return new Gt(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=$x(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 Gt(e.key,e.value,t)}};var j0=globalThis.CustomEvent??Event;async function*$o(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,s=[],o=Me(),a=Me(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(o=Me(),await o.promise),l)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,i.dispatchEvent(new j0("task-complete"))},g=>{m.done=!0,m.err=g,i.dispatchEvent(new j0("task-complete"))})}c=!0,i.dispatchEvent(new j0("task-complete"))}catch(p){u=p,i.dispatchEvent(new j0("task-complete"))}});function h(){return n?s[0]?.done:!!s.find(p=>p.done)}function*f(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,o.resolve(),p.err;o.resolve()}}function*d(){for(;h();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw l=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(h()||(a=Me(),await a.promise),u!=null)throw u;if(n?yield*f():yield*d(),c&&s.length===0)break}}var Gx;(function(r){let e;r.codec=()=>(e==null&&(e=se((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={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>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(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Gx||(Gx={}));var to;(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=()=>Ht(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=()=>Ht(i)}(n=r.ConnectionType||(r.ConnectionType={}));let s;(function(a){let c;a.codec=()=>(c==null&&(c=se((u,l,h={})=>{if(h.lengthDelimited!==!1&&l.fork(),u.id!=null&&(l.uint32(10),l.bytes(u.id)),u.addrs!=null)for(let f of u.addrs)l.uint32(18),l.bytes(f);u.connection!=null&&(l.uint32(24),r.ConnectionType.codec().encode(u.connection,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={addrs:[]},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.id=u.bytes();break;case 2:h.addrs.push(u.bytes());break;case 3:h.connection=r.ConnectionType.codec().decode(u);break;default:u.skipType(d&7);break}}return h})),c),a.encode=u=>ie(u,a.codec()),a.decode=u=>ne(u,a.codec())})(s=r.Peer||(r.Peer={}));let o;r.codec=()=>(o==null&&(o=se((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<l;){let h=a.uint32();switch(h>>>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(h&7);break}}return u})),o),r.encode=a=>ie(a,r.codec()),r.decode=a=>ne(a,r.codec())})(to||(to={}));var Vt=to.MessageType,iK=to.ConnectionType,Qx=Object.keys(Vt),St=class{type;key;clusterLevelRaw;closerPeers;providerPeers;record;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 to.encode({key:this.key,type:this.type,clusterLevelRaw:this.clusterLevelRaw,closerPeers:this.closerPeers.map(Wx),providerPeers:this.providerPeers.map(Wx),record:this.record==null?void 0:this.record.serialize().subarray()})}static deserialize(e){let t=to.decode(e),n=new St(t.type??to.MessageType.PUT_VALUE,t.key??Uint8Array.from([]),t.clusterLevelRaw??0);return n.closerPeers=t.closerPeers.map(Yx),n.providerPeers=t.providerPeers.map(Yx),t.record?.length!=null&&(n.record=Gt.deserialize(t.record)),n}};function Wx(r){return{id:r.id.toBytes(),addrs:(r.multiaddrs??[]).map(t=>t.bytes),connection:iK.CONNECTED}}function Yx(r){if(r.id==null)throw new Error("Invalid peer in message");return{id:It(r.id),multiaddrs:(r.addrs??[]).map(e=>re(e)),protocols:[]}}function o4(r,e={}){let t={...r,name:"SEND_QUERY",type:0,messageName:r.type,messageType:Qx.indexOf(r.type.toString())};return e.onProgress?.(new Je("kad-dht:query:send-query",{detail:t})),t}function xl(r,e={}){let t={...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer!=null?r.closer:[],providers:r.providers!=null?r.providers:[]};return e.onProgress?.(new Je("kad-dht:query:peer-response",{detail:t})),t}function Z0(r,e={}){let t={...r,name:"FINAL_PEER",type:2};return e.onProgress?.(new Je("kad-dht:query:final-peer",{detail:t})),t}function Br(r,e={}){let t={...r,name:"QUERY_ERROR",type:3};return e.onProgress?.(new Je("kad-dht:query:query-error",{detail:t})),t}function a4(r,e={}){let t={...r,name:"PROVIDER",type:4};return e.onProgress?.(new Je("kad-dht:query:provider",{detail:t})),t}function _l(r,e={}){let t={...r,name:"VALUE",type:5};return e.onProgress?.(new Je("kad-dht:query:value",{detail:t})),t}function c4(r,e={}){let t={...r,name:"DIAL_PEER",type:7};return e.onProgress?.(new Je("kad-dht:query:dial-peer",{detail:t})),t}var sK=q("/pk/");function mc(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=Nn(n);return i==null?!0:!i})}}function gc(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=Nn(n);return i??!1})}}async function ro(r){return(await Pe.digest(r)).digest}async function ii(r){return ro(r.toBytes())}function os(r){return new ve(`${zx}/${B(r,"base32")}`,!1)}function Xx(r){return he([sK,r.toBytes()])}function jx(r){return B(r.subarray(0,4))==="/pk/"}function Zx(r){return It(r.subarray(4))}function u4(r,e){let t=new Date;return new Gt(r,e,t).serialize()}function Jx(r,e=100){let t;return()=>{clearTimeout(t),t=setTimeout(()=>{r()},e)}}var J0=class{log;components;validators;selectors;peerRouting;queryManager;network;constructor(e,t){let{validators:n,selectors:i,peerRouting:s,queryManager:o,network:a,lan:c}=t;this.components=e,this.log=D(`libp2p:kad-dht:${c?"lan":"wan"}:content-fetching`),this.validators=n,this.selectors=i,this.peerRouting=s,this.queryManager=o,this.network=a}async putLocal(e,t){let n=os(e);await this.components.datastore.put(n,t)}async getLocal(e){this.log("getLocal %b",e);let t=os(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=Gt.deserialize(n);return await pc(this.validators,i),i}async*sendCorrectionRecord(e,t,n,i={}){this.log("sendCorrection for %b",e);let s=u4(e,n);for(let{value:o,from:a}of t){if(pe(o,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let l=os(e);this.log(`Storing corrected record for key ${l.toString()}`),await this.components.datastore.put(l,s.subarray())}catch(l){this.log.error("Failed error correcting self",l)}continue}let c=!1,u=new St(Vt.PUT_VALUE,e,0);u.record=Gt.deserialize(s);for await(let l of this.network.sendRequest(a,u,i))l.name==="PEER_RESPONSE"&&l.record!=null&&pe(l.record.value,Gt.deserialize(s).value)&&(c=!0),yield l;c||(yield Br({from:a,error:new w("value not put correctly","ERR_PUT_VALUE_INVALID")},i)),this.log.error("Failed error correcting entry")}}async*put(e,t,n={}){this.log("put key %b value %b",e,t);let i=u4(e,t),s=os(e);this.log(`storing record for key ${s.toString()}`),await this.components.datastore.put(s,i.subarray()),yield*be(this.peerRouting.getClosestPeers(e,{signal:n.signal}),o=>Kn(o,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],u=new St(Vt.PUT_VALUE,e,0);u.record=Gt.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&&pe(l.record.value,Gt.deserialize(i).value)||c.push(Br({from:a.peer.id,error:new w("value not put correctly","ERR_PUT_VALUE_INVALID")},n)));return c}),o=>$o(o,{ordered:!1,concurrency:3}),async function*(o){for await(let a of o)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),s=0;try{s=Mx(this.selectors,e,i)}catch(a){if(a.code!=="ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY")throw a}let o=i[s];if(this.log("GetValue %b %b",e,o),o==null)throw new w("best value was not found","ERR_NOT_FOUND");yield*this.sendCorrectionRecord(e,n,o,t),yield n[s]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let s=await this.getLocal(e);yield _l({value:s.value,from:this.components.peerId},t)}catch(s){this.log("error getting local value for %b",e,s)}let n=this,i=async function*({peer:s,signal:o}){for await(let a of n.peerRouting.getValueOrPeers(s,e,{signal:o}))yield a,a.name==="PEER_RESPONSE"&&a.record!=null&&(yield _l({from:s,value:a.record.value},t))};yield*this.queryManager.run(e,i,t)}};var e1=class{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){let{network:n,peerRouting:i,queryManager:s,routingTable:o,providers:a,lan:c}=t;this.components=e,this.log=D(`libp2p:kad-dht:${c?"lan":"wan"}:content-routing`),this.network=n,this.peerRouting=i,this.queryManager=s,this.routingTable=o,this.providers=a}async*provide(e,t,n={}){this.log("provide %s",e),await this.providers.addProvider(e,this.components.peerId);let i=new St(Vt.ADD_PROVIDER,e.multihash.bytes,0);i.providerPeers=[{id:this.components.peerId,multiaddrs:t,protocols:[]}];let s=0,o=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),s++),c.push(u)}catch(u){this.log.error("error sending provide record to peer %p",a.peer.id,u),c.push(Br({from:a.peer.id,error:u},n))}return c};yield*be(this.peerRouting.getClosestPeers(e.multihash.bytes,n),a=>Kn(a,c=>o(c)),a=>$o(a,{ordered:!1,concurrency:3}),async function*(a){for await(let c of a)yield*c}),this.log("sent provider records to %d peers",s)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,i=e.multihash.bytes,s=this;this.log("findProviders %c",e);let o=await this.providers.getProviders(e);if(o.length>0){let u=[];for(let l of o.slice(0,n))try{let h=await this.components.peerStore.get(l);u.push({id:l,multiaddrs:h.addresses.map(({multiaddr:f})=>f),protocols:h.protocols})}catch(h){if(h.code!=="ERR_NOT_FOUND")throw h;this.log("no peer store entry for %p",l)}yield xl({from:this.components.peerId,messageType:Vt.GET_PROVIDERS,providers:u},t),yield a4({from:this.components.peerId,providers:u},t)}if(o.length>=n)return;let a=async function*({peer:u,signal:l}){let h=new St(Vt.GET_PROVIDERS,i,0);yield*s.network.sendRequest(u,h,{...t,signal:l})},c=new Set(o.map(u=>u.toString()));for await(let u of this.queryManager.run(i,a,t))if(yield u,u.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",u.providers.length,e,u.closer.length);let l=[];for(let h of u.providers)c.has(h.id.toString())||(c.add(h.id.toString()),l.push(h));if(l.length>0&&(yield a4({from:u.from,providers:l},t)),c.size===n)return}}};function oK(r){return r[Symbol.asyncIterator]!=null}function aK(r){if(oK(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var si=aK;var t1=class extends Ue{log;protocol;running;components;constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=D(`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 c4({peer:e},n),yield o4({to:e,type:t.type},n);let i;try{let o=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n),a=await this._writeReadMessage(o,t.serialize(),n);yield xl({from:e,messageType:a.type,closer:a.closerPeers,providers:a.providerPeers,record:a.record},n)}catch(s){yield Br({from:e,error:s},n)}finally{i?.close()}}async*sendMessage(e,t,n={}){if(!this.running)return;this.log("sending %s to %p",t.type,e),yield c4({peer:e},n),yield o4({to:e,type:t.type},n);let i;try{let o=await(await this.components.connectionManager.openConnection(e,n)).newStream(this.protocol,n);await this._writeMessage(o,t.serialize(),n),yield xl({from:e,messageType:t.type},n)}catch(s){yield Br({from:e,error:s},n)}finally{i?.close()}}async _writeMessage(e,t,n){n.signal!=null&&(e=Er(e,n.signal)),await be([t],i=>Et(i),e,Yr)}async _writeReadMessage(e,t,n){n.signal!=null&&(e=Er(e,n.signal));let i=await be([t],o=>Et(o),e,o=>Ct(o),async o=>{let a=await si(o);if(a!=null)return a;throw new w("No message received","ERR_NO_MESSAGE_RECEIVED")}),s=St.deserialize(i);return s.closerPeers.forEach(o=>{this.dispatchEvent(new Je("peer",{detail:o}))}),s.providerPeers.forEach(o=>{this.dispatchEvent(new Je("peer",{detail:o}))}),s}};var r1=class{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map(e=>e.peerId)}async add(e){if(this.peerDistances.find(i=>i.peerId.equals(e))!=null)return;let t=await ii(e),n={peerId:e,distance:is(this.originDhtKey,t)};this.peerDistances.push(n),this.peerDistances.sort((i,s)=>D0(i.distance,s.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(ii)),n=this.peerDistances[this.peerDistances.length-1].distance;for(let i of t){let s=is(this.originDhtKey,i);if(D0(s,n)<0)return!0}return!1}};var n1=class{components;log;routingTable;network;validators;queryManager;constructor(e,t){let{routingTable:n,network:i,validators:s,queryManager:o,lan:a}=t;this.components=e,this.routingTable=n,this.network=i,this.validators=s,this.queryManager=o,this.log=D(`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 St(Vt.GET_VALUE,t,0);yield*this.network.sendRequest(e,i,n)}async*getPublicKeyFromNode(e,t={}){let n=Xx(e);for await(let i of this._getValueSingle(e,n,t))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let s=await er(jf.marshalPublicKey({bytes:i.record.value}));if(!s.equals(e))throw new w("public key does not match id","ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID");if(s.publicKey==null)throw new w("public key missing","ERR_PUBLIC_KEY_MISSING");yield _l({from:e,value:s.publicKey},t)}throw new w(`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 Z0({from:this.components.peerId,peer:n},t);return}let i=this,s=async function*({peer:a,signal:c}){let u=new St(Vt.FIND_NODE,e.toBytes(),0);for await(let l of i.network.sendRequest(a,u,{...t,signal:c}))if(yield l,l.name==="PEER_RESPONSE"){let h=l.closer.find(f=>f.id.equals(e));h!=null&&(yield Z0({from:l.from,peer:h},t))}},o=!1;for await(let a of this.queryManager.run(e.toBytes(),s,t))a.name==="FINAL_PEER"&&(o=!0),yield a;o||(yield Br({from:this.components.peerId,error:new w("Not found","ERR_NOT_FOUND")},t))}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await ro(e),i=this.routingTable.closestPeers(n),s=this,o=new r1(n,this.routingTable.kBucketSize);await Promise.all(i.map(async c=>{await o.add(c)}));let a=async function*({peer:c,signal:u}){s.log("closerPeersSingle %s from %p",B(e,"base32"),c);let l=new St(Vt.FIND_NODE,e,0);yield*s.network.sendRequest(c,l,{...t,signal:u})};for await(let c of this.queryManager.run(e,a,t))yield c,c.name==="PEER_RESPONSE"&&await Promise.all(c.closer.map(async u=>{await o.add(u.id)}));this.log("found %d peers close to %b",o.length,e);for(let c of o.peers)try{let u=await this.components.peerStore.get(c);yield Z0({from:this.components.peerId,peer:{id:c,multiaddrs:u.addresses.map(({multiaddr:l})=>l),protocols:u.protocols}},t)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}}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 o="invalid record received, discarded";this.log(o),yield Br({from:i.from,error:new w(o,"ERR_INVALID_RECORD")},n);continue}yield i}}async _verifyRecordOnline(e){if(e.timeReceived==null)throw new w("invalid record received","ERR_INVALID_RECORD");await pc(this.validators,new Gt(e.key,e.value,e.timeReceived))}async getCloserPeersOffline(e,t){let n=await ro(e),i=this.routingTable.closestPeers(n),s=[];for(let o of i)if(!o.equals(t))try{let a=await this.components.peerStore.get(o);s.push({id:o,multiaddrs:a.addresses.map(({multiaddr:c})=>c),protocols:a.protocols})}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}return s.length>0?this.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",s.length,e,t):this.log("getCloserPeersOffline could not find peer closer to %b than %p",e,t),s}};var r_=F(t_(),1);var h4=F(bo(),1);var as=D("libp2p:kad-dht:providers"),i1=class{components;cache;cleanupInterval;provideValidity;syncQueue;started;cleaner;constructor(e,t={}){let{cacheSize:n,cleanupInterval:i,provideValidity:s}=t;this.components=e,this.cleanupInterval=i??36e5,this.provideValidity=s??864e5,this.cache=(0,r_.default)(n??256),this.syncQueue=new vt({concurrency:1}),this.started=!1}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cleaner=setInterval(()=>{this._cleanup().catch(e=>{as.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,s=this.components.datastore.batch(),o=this.components.datastore.query({prefix:s4});for await(let a of o)try{let{cid:c,peerId:u}=n_(a.key),l=i_(a.value).getTime(),h=Date.now(),f=h-l,d=f>this.provideValidity;if(as("comparing: %d - %d = %d > %d %s",h,l,f,this.provideValidity,d?"(expired)":""),d){n++,s.delete(a.key);let p=i.get(c)??new Set;p.add(u),i.set(c,p)}t++}catch(c){as.error(c.message)}i.size>0?(as("deleting %d / %d entries",n,t),await s.commit()):as("nothing to delete");for(let[a,c]of i){let u=Sl(a),l=this.cache.get(u);if(l!=null){for(let h of c)l.delete(h);l.size===0?this.cache.remove(u):this.cache.set(u,l)}}as("Cleanup successful (%dms)",Date.now()-e)})}async _getProvidersMap(e){let t=Sl(e),n=this.cache.get(t);return n==null&&(n=await fK(this.components.datastore,e),this.cache.set(t,n)),n}async addProvider(e,t){await this.syncQueue.add(async()=>{as("%p provides %s",t,e);let n=await this._getProvidersMap(e);as("loaded %s provs",n.size);let i=new Date;n.set(t.toString(),i);let s=Sl(e);this.cache.set(s,n),await hK(this.components.datastore,e,t,i)})}async getProviders(e){return this.syncQueue.add(async()=>(as("get providers for %s",e),[...(await this._getProvidersMap(e)).keys()].map(n=>oe(n))),{throwOnTimeout:!0})}};function Sl(r){let e=typeof r=="string"?r:B(r.multihash.bytes,"base32");return`${s4}/${e}`}async function hK(r,e,t,n){let i=[Sl(e),"/",t.toString()].join(""),s=new ve(i),o=Uint8Array.from(h4.default.encode(n.getTime()));await r.put(s,o)}function n_(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 fK(r,e){let t=new Map,n=r.query({prefix:Sl(e)});for await(let i of n){let{peerId:s}=n_(i.key);t.set(s,i_(i.value))}return t}function i_(r){return new Date(h4.default.decode(r))}var Go=F(Zr(),1);function cs(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 Mr=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 cs(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 cs(this.map.keys(),e=>oe(e))}values(){return this.map.values()}get size(){return this.map.size}};var Rr=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 cs(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 cs(this.set.values(),e=>oe(e))}intersection(e){let t=new Rr;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new Rr;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new Rr;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var wc=class{constructor(e){if(this.list=[],e!=null)for(let t of e)this.list.push(t.toString())}[Symbol.iterator](){return cs(this.list.entries(),e=>oe(e[1]))}concat(e){let t=new wc(this);for(let n of e)t.push(n);return t}entries(){return cs(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 wc;return this.list.forEach((n,i)=>{let s=oe(n);e(s,i,this)&&t.push(s)}),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 dK=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");async function*s_(r){let{key:e,startingPeer:t,ourPeerId:n,signal:i,query:s,alpha:o,pathIndex:a,numPaths:c,cleanUp:u,queryFuncTimeout:l,log:h,peersSeen:f}=r,d=new vt({concurrency:o}),p=await ro(e);function m(g,y){if(g==null)return;f.add(g);let b=BigInt("0x"+B(is(y,p),"base16"));d.add(async()=>{let E=[i];l!=null&&E.push(AbortSignal.timeout(l));let R=it(E);try{for await(let v of s({key:e,peer:g,signal:R,pathIndex:a,numPaths:c})){if(R.aborted)return;if(v.name==="PEER_RESPONSE")for(let _ of v.closer){if(f.has(_.id)){h("already seen %p in query",_.id);continue}if(n.equals(_.id)){h("not querying ourselves");continue}let I=await ii(_.id);if(BigInt("0x"+B(is(I,p),"base16"))>b){h("skipping %p as they are not closer to %b than %p",_.id,e,g);continue}h("querying closer peer %p",_.id),m(_.id,I)}d.emit("completed",v)}}catch(v){if(!i.aborted)return Br({from:g,error:v},r)}finally{R.clear()}},{priority:dK-b}).catch(E=>{h.error(E)})}m(t,await ii(t)),yield*pK(d,i,u,h)}async function*pK(r,e,t,n){let i=Me(),s=!0,o=[],a=()=>{s&&(n("clean up queue, results %d, queue size %d, pending tasks %d",o.length,r.size,r.pending),s=!1,r.clear(),o.splice(0,o.length))};for(r.on("completed",c=>{o.push(c),i.resolve()}),r.on("error",c=>{n("queue error",c),a(),i.reject(c)}),r.on("idle",()=>{n("queue idle"),s=!1,i.resolve()}),e.addEventListener("abort",()=>{n("abort queue");let c=s;a(),c&&i.reject(new w("Query aborted","ERR_QUERY_ABORTED"))}),t.addEventListener("cleanup",()=>{a(),i.resolve()});s;)for(await i.promise,i=Me();o.length>0;){let c=o.shift();c!=null&&(yield c)}yield*o}var o1=class{components;lan;disjointPaths;alpha;shutDownController;running;queries;metrics;routingTable;initialQuerySelfHasRun;constructor(e,t){let{lan:n=!1,disjointPaths:i=20,alpha:s=3}=t;this.components=e,this.disjointPaths=i??20,this.running=!1,this.alpha=s??3,this.lan=n,this.queries=0,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.shutDownController=new AbortController;try{Go.setMaxListeners!=null&&(0,Go.setMaxListeners)(1/0,this.shutDownController.signal)}catch{}}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,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");let i=this.metrics?.queryTime.timer();if(n.signal==null){n.signal=AbortSignal.timeout(3e4);try{Go.setMaxListeners!=null&&(0,Go.setMaxListeners)(1/0,n.signal)}catch{}}let s=it([this.shutDownController.signal,n.signal]);try{Go.setMaxListeners!=null&&(0,Go.setMaxListeners)(1/0,s)}catch{}let o=D(`libp2p:kad-dht:${this.lan?"lan":"wan"}:query:`+B(e,"base58btc")),a=Date.now(),c=new Ue;try{n.isSelfQuery!==!0&&this.initialQuerySelfHasRun!=null&&(o("waiting for initial query-self query before continuing"),await Promise.race([new Promise((p,m)=>{s.addEventListener("abort",()=>{m(new Xr("Query was aborted before self-query ran"))})}),this.initialQuerySelfHasRun.promise]),this.initialQuerySelfHasRun=void 0),o("query:start"),this.queries++,this.metrics?.runningQueries.update(this.queries);let u=await ro(e),l=this.routingTable.closestPeers(u),h=l.slice(0,Math.min(this.disjointPaths,l.length));if(l.length===0){o.error("Running query with no peers");return}let f=new Rr,d=h.map((p,m)=>s_({key:e,startingPeer:p,ourPeerId:this.components.peerId,signal:s,query:t,pathIndex:m,numPaths:h.length,alpha:this.alpha,cleanUp:c,queryFuncTimeout:n.queryFuncTimeout,log:o,peersSeen:f,onProgress:n.onProgress}));for await(let p of jt(...d))yield p,p.name==="QUERY_ERROR"&&o("error",p.error)}catch(u){if(!(!this.running&&u.code==="ERR_QUERY_ABORTED"))throw u}finally{s.clear(),this.queries--,this.metrics?.runningQueries.update(this.queries),i?.(),c.dispatchEvent(new Je("cleanup")),o("query:done in %dms",Date.now()-a)}}};var f4=F(Zr(),1);function gK(r){return r[Symbol.asyncIterator]!=null}function yK(r){if(gK(r))return(async()=>{let e=0;for await(let t of r)e++;return e})();{let e=0;for(let t of r)e++;return e}}var a1=yK;function vK(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var c1=class{log;components;peerRouting;routingTable;count;interval;initialInterval;queryTimeout;started;running;timeoutId;controller;initialQuerySelfHasRun;constructor(e,t){let{peerRouting:n,lan:i,count:s,interval:o,queryTimeout:a,routingTable:c}=t;this.components=e,this.log=D(`libp2p:kad-dht:${i?"lan":"wan"}:query-self`),this.running=!1,this.started=!1,this.peerRouting=n,this.routingTable=c,this.count=s??20,this.interval=o??3e5,this.initialInterval=t.initialInterval??1e3,this.queryTimeout=a??5e3,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.querySelf=vK(this.querySelf.bind(this),100)}isStarted(){return this.started}async start(){this.started||(this.started=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(this.querySelf.bind(this),this.initialInterval))}async stop(){this.started=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}querySelf(){if(!this.started){this.log("skip self-query because we are not started");return}if(this.running){this.log("skip self-query because we are already running, will run again in %dms",this.interval);return}if(this.routingTable.size===0){let e=this.interval;this.initialQuerySelfHasRun!=null&&(e=this.initialInterval),this.log("skip self-query because routing table is empty, will run again in %dms",e),clearTimeout(this.timeoutId),this.timeoutId=setTimeout(this.querySelf.bind(this),e);return}this.running=!0,Promise.resolve().then(async()=>{if(!this.started){this.log("not running self-query - node stopped before query started");return}this.controller=new AbortController;let e=it([this.controller.signal,AbortSignal.timeout(this.queryTimeout)]);try{f4.setMaxListeners!=null&&(0,f4.setMaxListeners)(1/0,e)}catch{}try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);let t=await be(this.peerRouting.getClosestPeers(this.components.peerId.toBytes(),{signal:e,isSelfQuery:!0}),n=>gs(n,this.count),async n=>a1(n));this.log("self-query ran successfully - found %d peers",t),this.initialQuerySelfHasRun!=null&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}catch(t){this.log.error("self-query error",t)}finally{e.clear()}}).catch(e=>{this.log("self-query error",e)}).finally(()=>{this.running=!1,clearTimeout(this.timeoutId),this.started&&(this.log("running self-query again in %dms",this.interval),this.timeoutId=setTimeout(this.querySelf.bind(this),this.interval))})}};function o_(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0,n=r.length;t<n;++t)if(r[t]!==e[t])return!1;return!0}function d4(){return{contacts:[],dontSplit:!1,left:null,right:null}}function Al(r,e){if(!(e instanceof Uint8Array))throw new TypeError(r+" is not a Uint8Array")}var Wo=class extends Ue{localNodeId;root;numberOfNodesPerKBucket;numberOfNodesToPing;distance;arbiter;constructor(e){super(),this.localNodeId=e.localNodeId,this.numberOfNodesPerKBucket=e.numberOfNodesPerKBucket??20,this.numberOfNodesToPing=e.numberOfNodesToPing??3,this.distance=e.distance??Wo.distance,this.arbiter=e.arbiter??Wo.arbiter,Al("option.localNodeId as parameter 1",this.localNodeId),this.root=d4()}static arbiter(e,t){return(e.vectorClock??0)>(t.vectorClock??0)?e:t}static distance(e,t){let n=0,i=0,s=Math.min(e.length,t.length),o=Math.max(e.length,t.length);for(;i<s;++i)n=n*256+(e[i]^t[i]);for(;i<o;++i)n=n*256+255;return n}add(e){Al("contact.id",e?.id);let t=0,n=this.root;for(;n.contacts===null;)n=this._determineNode(n,e.id,t++);let i=this._indexOf(n,e.id);return i>=0?(this._update(n,i,e),this):n.contacts.length<this.numberOfNodesPerKBucket?(n.contacts.push(e),this.safeDispatchEvent("added",{detail:e}),this):n.dontSplit?(this.safeDispatchEvent("ping",{detail:{oldContacts:n.contacts.slice(0,this.numberOfNodesToPing),newContact:e}}),this):(this._split(n,t),this.add(e))}closest(e,t=1/0){if(Al("id",e),!Number.isInteger(t)&&t!==1/0||t<=0)throw new TypeError("n is not positive number");let n=[];for(let i=[this.root],s=0;i.length>0&&n.length<t;){let o=i.pop();if(o!=null)if(o.contacts===null){let a=this._determineNode(o,e,s++);i.push(o.left===a?o.right:o.left),i.push(a)}else n=n.concat(o.contacts)}return n.map(i=>({distance:this.distance(i.id,e),contact:i})).sort((i,s)=>i.distance-s.distance).slice(0,t).map(i=>i.contact)}count(){let e=0;for(let t=[this.root];t.length>0;){let n=t.pop();n!=null&&(n.contacts===null?t.push(n.right,n.left):e+=n.contacts.length)}return e}_determineNode(e,t,n){let i=n>>3,s=n%8;return t.length<=i&&s!==0?e.left:t[i]&1<<7-s?e.right:e.left}get(e){Al("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]:void 0}_indexOf(e,t){for(let n=0;n<e.contacts.length;++n)if(o_(e.contacts[n].id,t))return n;return-1}remove(e){Al("the id as parameter 1",e);let t=0,n=this.root;for(;n.contacts===null;)n=this._determineNode(n,e,t++);let i=this._indexOf(n,e);if(i>=0){let s=n.contacts.splice(i,1)[0];this.safeDispatchEvent("removed",{detail:s})}return this}_split(e,t){e.left=d4(),e.right=d4();for(let s of e.contacts)this._determineNode(e,s.id,t).contacts.push(s);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!=null&&(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!=null&&(t.contacts===null?e.push(t.right,t.left):yield*t.contacts)}}_update(e,t,n){if(!o_(e.contacts[t].id,n.id))throw new Error("wrong index for _update");let i=e.contacts[t],s=this.arbiter(i,n);s===i&&i!==n||(e.contacts.splice(t,1),e.contacts.push(s),this.safeDispatchEvent("updated",{detail:{incumbent:i,selection:s}}))}};var xK="kad-close",_K=50,a_=20,SK=1e4,AK=10,u1=class{kBucketSize;kb;pingQueue;log;components;lan;pingTimeout;pingConcurrency;running;protocol;tagName;tagValue;metrics;constructor(e,t){let{kBucketSize:n,pingTimeout:i,lan:s,pingConcurrency:o,protocol:a,tagName:c,tagValue:u}=t;this.components=e,this.log=D(`libp2p:kad-dht:${s?"lan":"wan"}:routing-table`),this.kBucketSize=n??a_,this.pingTimeout=i??SK,this.pingConcurrency=o??AK,this.lan=s,this.running=!1,this.protocol=a,this.tagName=c??xK,this.tagValue=u??_K;let l=()=>{this.metrics?.pingQueueSize.update(this.pingQueue.size),this.metrics?.pingRunning.update(this.pingQueue.pending)};this.pingQueue=new vt({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 Wo({localNodeId:await ii(this.components.peerId),numberOfNodesPerKBucket:this.kBucketSize,numberOfNodesToPing:1});this.kb=e,e.addEventListener("ping",this._onPing),this._tagPeers(e)}async stop(){this.running=!1,this.pingQueue.clear(),this.kb=void 0}_tagPeers(e){let t=new Rr,n=Jx(()=>{let i=new Rr(e.closest(e.localNodeId,a_).map(a=>a.peer)),s=i.difference(t),o=t.difference(i);Promise.resolve().then(async()=>{for(let a of s)await this.components.peerStore.merge(a,{tags:{[this.tagName]:{value:this.tagValue}}});for(let a of o)await this.components.peerStore.merge(a,{tags:{[this.tagName]:void 0}})}).catch(a=>{this.log.error("Could not update peer tags",a)}),t=i});e.addEventListener("added",()=>{n()}),e.addEventListener("removed",()=>{n()})}_onPing(e){let{oldContacts:t,newContact:n}=e.detail;this.pingQueue.add(async()=>{if(!this.running)return;let i=0;try{await Promise.all(t.map(async s=>{try{let o={signal:AbortSignal.timeout(this.pingTimeout)};this.log("pinging old contact %p",s.peer),(await(await this.components.connectionManager.openConnection(s.peer,o)).newStream(this.protocol,o)).close(),i++}catch(o){this.running&&this.kb!=null&&(this.log.error("could not ping peer %p",s.peer,o),this.log("evicting old contact after ping failed %p",s.peer),this.kb.remove(s.id))}finally{this.metrics?.routingTableSize.update(this.size)}})),this.running&&i<t.length&&this.kb!=null&&(this.log("adding new contact %p",n.peer),this.kb.add(n))}catch(s){this.log.error("could not process k-bucket ping event",s)}}).catch(i=>{this.log.error("could not process k-bucket ping event",i)})}get size(){return this.kb==null?0:this.kb.count()}async find(e){let t=await ii(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){if(this.kb==null)throw new Error("RoutingTable is not started");let t=await ii(e);this.kb.add({id:t,peer:e}),this.log("added %p with kad id %b",e,t),this.metrics?.routingTableSize.update(this.size)}async remove(e){if(this.kb==null)throw new Error("RoutingTable is not started");let t=await ii(e);this.kb.remove(t),this.metrics?.routingTableSize.update(this.size)}};var c_=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];var l1=15,h1=class{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e){let{peerRouting:t,routingTable:n,refreshInterval:i,refreshQueryTimeout:s,lan:o}=e;this.log=D(`libp2p:kad-dht:${o?"lan":"wan"}:routing-table:refresh`),this.peerRouting=t,this.routingTable=n,this.refreshInterval=i??3e5,this.refreshQueryTimeout=s??3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async start(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){this.refreshTimeoutId!=null&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1){this.log("refreshing routing table");let t=this._maxCommonPrefix(),n=this._getTrackedCommonPrefixLengthsForRefresh(t);this.log(`max common prefix length ${t}`),this.log(`tracked CPLs [ ${n.map(i=>i.toISOString()).join(", ")} ]`),Promise.all(n.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e),this._numPeersForCpl(t)===0){let o=Math.min(2*(s+1),n.length-1);for(let a=s+1;a<o+1;a++)try{await this._refreshCommonPrefixLength(a,i,e)}catch(c){this.log.error(c)}}}catch(o){this.log.error(o)}})).catch(i=>{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 s=await a1(this.peerRouting.getClosestPeers(i.toBytes(),{signal:AbortSignal.timeout(this.refreshQueryTimeout)}));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)}_getTrackedCommonPrefixLengthsForRefresh(e){e>l1&&(e=l1);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=Cn(2),n=(t[1]<<8)+t[0],i=await this._makePeerId(this.routingTable.kb.localNodeId,n,e);return It(i)}async _makePeerId(e,t,n){if(n>l1)throw new Error(`Cannot generate peer ID for common prefix length greater than ${l1}`);let o=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=o&a|t&~a,u=c_[c],l=new ArrayBuffer(34),h=new DataView(l,0,l.byteLength);return h.setUint8(0,Pe.code),h.setUint8(1,32),h.setUint32(2,u,!1),new Uint8Array(h.buffer,h.byteOffset,h.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=is(this.routingTable.kb.localNodeId,e),n=0;for(let i of t)if(i===0)n++;else break;yield n}}};var Rl=D("libp2p:kad-dht:rpc:handlers:add-provider"),f1=class{providers;constructor(e){let{providers:t}=e;this.providers=t}async handle(e,t){if(Rl("start"),t.key==null||t.key.length===0)throw new w("Missing key","ERR_MISSING_KEY");let n;try{n=ee.decode(t.key)}catch{throw new w("Invalid CID","ERR_INVALID_CID")}(t.providerPeers==null||t.providerPeers.length===0)&&Rl.error("no providers found in message"),await Promise.all(t.providerPeers.map(async i=>{if(!i.id.equals(e)){Rl("invalid provider peer %p from %p",i.id,e);return}if(i.multiaddrs.length<1){Rl("no valid addresses for provider %p. Ignore",e);return}Rl("received provider %p for %s (addrs %s)",e,n,i.multiaddrs.map(s=>s.toString())),await this.providers.addProvider(n,i.id)}))}};var u_=D("libp2p:kad-dht:rpc:handlers:find-node"),d1=class{peerRouting;lan;components;constructor(e,t){let{peerRouting:n,lan:i}=t;this.components=e,this.peerRouting=n,this.lan=!!i}async handle(e,t){u_("incoming request from %p for peers closer to %b",e,t.key);let n=[];pe(this.components.peerId.toBytes(),t.key)?n=[{id:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(s=>s.decapsulateCode(X("p2p").code)),protocols:[]}]:n=await this.peerRouting.getCloserPeersOffline(t.key,e),n=n.map(this.lan?gc:mc).filter(({multiaddrs:s})=>s.length);let i=new St(t.type,new Uint8Array(0),t.clusterLevel);return n.length>0?i.closerPeers=n:u_("could not find any peers closer to %b than %p",t.key,e),i}};var l_=D("libp2p:kad-dht:rpc:handlers:get-providers"),p1=class{components;peerRouting;providers;lan;constructor(e,t){let{peerRouting:n,providers:i,lan:s}=t;this.components=e,this.peerRouting=n,this.providers=i,this.lan=!!s}async handle(e,t){let n;try{n=ee.decode(t.key)}catch{throw new w("Invalid CID","ERR_INVALID_CID")}l_("%p asking for providers for %s",e,n);let[i,s]=await Promise.all([this.providers.getProviders(n),this.peerRouting.getCloserPeersOffline(t.key,e)]),o=await this._getPeers(i),a=await this._getPeers(s.map(({id:u})=>u)),c=new St(t.type,t.key,t.clusterLevel);return o.length>0&&(c.providerPeers=o),a.length>0&&(c.closerPeers=a),l_("got %s providers %s closerPeers",o.length,a.length),c}async _getAddresses(e){return[]}async _getPeers(e){let t=[],n=this.lan?gc:mc;for(let i of e)try{let s=await this.components.peerStore.get(i),o=n({id:i,multiaddrs:s.addresses.map(({multiaddr:a})=>a),protocols:s.protocols});o.multiaddrs.length>0&&t.push(o)}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}return t}};var bc=D("libp2p:kad-dht:rpc:handlers:get-value"),m1=class{components;peerRouting;constructor(e,t){let{peerRouting:n}=t;this.components=e,this.peerRouting=n}async handle(e,t){let n=t.key;if(bc("%p asked for key %b",e,n),n==null||n.length===0)throw new w("Invalid key","ERR_INVALID_KEY");let i=new St(Vt.GET_VALUE,n,t.clusterLevel);if(jx(n)){bc("is public key");let a=Zx(n),c;try{let u=await this.components.peerStore.get(a);if(u.id.publicKey==null)throw new w("No public key found in key book","ERR_NOT_FOUND");c=u.id.publicKey}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(c!=null)return bc("returning found public key"),i.record=new Gt(n,c,new Date),i}let[s,o]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getCloserPeersOffline(t.key,e)]);return s!=null&&(bc("had record for %b in local datastore",n),i.record=s),o.length>0&&(bc("had %s closer peers in routing table",o.length),i.closerPeers=o),i}async _checkLocalDatastore(e){bc("checkLocalDatastore looking for %b",e);let t=os(e),n;try{n=await this.components.datastore.get(t)}catch(s){if(s.code==="ERR_NOT_FOUND")return;throw s}let i=Gt.deserialize(n);if(i==null)throw new w("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 DK=D("libp2p:kad-dht:rpc:handlers:ping"),g1=class{async handle(e,t){return DK("ping from %p",e),t}};var y1=class{log;components;validators;constructor(e,t){let{validators:n}=t;this.components=e,this.log=D("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 s=`Empty record from: ${e.toString()}`;throw this.log.error(s),new w(s,"ERR_EMPTY_RECORD")}try{await pc(this.validators,i),i.timeReceived=new Date;let s=os(i.key);await this.components.datastore.put(s,i.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,s)}catch(s){this.log("did not put record for key %b into datastore %o",n,s)}return t}};var w1=class{handlers;routingTable;log;constructor(e,t){let{providers:n,peerRouting:i,validators:s,lan:o}=t;this.log=D("libp2p:kad-dht:rpc"),this.routingTable=t.routingTable,this.handlers={[Vt.GET_VALUE]:new m1(e,{peerRouting:i}),[Vt.PUT_VALUE]:new y1(e,{validators:s}),[Vt.FIND_NODE]:new d1(e,{peerRouting:i,lan:o}),[Vt.ADD_PROVIDER]:new f1({providers:n}),[Vt.GET_PROVIDERS]:new p1(e,{peerRouting:i,providers:n,lan:o}),[Vt.PING]:new g1}}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 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(o){this.log.error(o)}let s=this;await be(t,o=>Ct(o),async function*(o){for await(let a of o){let c=St.deserialize(a);s.log("incoming %s from %p",c.type,i);let u=await s.handleMessage(i,c);u!=null&&(yield u.serialize())}},o=>Et(o),t)}).catch(t=>{this.log.error(t)})}};var b1=class extends Ue{log;components;protocol;running;registrarId;constructor(e,t){super();let{protocol:n,lan:i}=t;this.components=e,this.log=D(`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=Es({onConnect:t=>{this.log("observed peer %p with protocol %s",t,this.protocol),this.dispatchEvent(new Je("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 CK=32,PK=64,Il=class extends Ue{protocol;routingTable;providers;network;peerRouting;components;log;running;kBucketSize;clientMode;lan;validators;selectors;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;constructor(e,t){super();let{kBucketSize:n,clientMode:i,validators:s,selectors:o,querySelfInterval:a,lan:c,protocolPrefix:u,pingTimeout:l,pingConcurrency:h,maxInboundStreams:f,maxOutboundStreams:d,providers:p}=t;this.running=!1,this.components=e,this.lan=!!c,this.log=D(`libp2p:kad-dht:${c===!0?"lan":"wan"}`),this.protocol=`${u??qx}${c===!0?Kx:""}${Vx}`,this.kBucketSize=n??20,this.clientMode=i??!0,this.maxInboundStreams=f??CK,this.maxOutboundStreams=d??PK,this.routingTable=new u1(e,{kBucketSize:n,lan:this.lan,pingTimeout:l,pingConcurrency:h,protocol:this.protocol}),this.providers=new i1(e,p??{}),this.validators={...Fx,...s},this.selectors={...Ux,...o},this.network=new t1(e,{protocol:this.protocol,lan:this.lan});let m=Me();t.allowQueryWithZeroPeers===!0&&m.resolve(),this.queryManager=new o1(e,{disjointPaths:Math.ceil(this.kBucketSize/2),lan:c,initialQuerySelfHasRun:m,routingTable:this.routingTable}),this.peerRouting=new n1(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,lan:this.lan}),this.contentFetching=new J0(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,lan:this.lan}),this.contentRouting=new e1(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,lan:this.lan}),this.routingTableRefresh=new h1({peerRouting:this.peerRouting,routingTable:this.routingTable,lan:this.lan}),this.rpc=new w1(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,lan:this.lan}),this.topologyListener=new b1(e,{protocol:this.protocol,lan:this.lan}),this.querySelf=new c1(e,{peerRouting:this.peerRouting,interval:a,initialInterval:t.initialQuerySelfInterval,lan:this.lan,initialQuerySelfHasRun:m,routingTable:this.routingTable}),this.network.addEventListener("peer",g=>{let y=g.detail;this.onPeerConnect(y).catch(b=>{this.log.error("could not add %p to routing table",y.id,b)}),this.dispatchEvent(new Je("peer",{detail:y}))}),this.topologyListener.addEventListener("peer",g=>{let y=g.detail;Promise.resolve().then(async()=>{let b=await this.components.peerStore.get(y),E={id:y,multiaddrs:b.addresses.map(({multiaddr:R})=>R),protocols:b.protocols};await this.onPeerConnect(E)}).catch(b=>{this.log.error("could not add %p to routing table",y,b)})})}async onPeerConnect(e){if(this.log("peer %p connected with protocols",e.id,e.protocols),this.lan?e=gc(e):e=mc(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 Ec=D("libp2p:kad-dht"),p4=class{dht;constructor(e){this.dht=e}async provide(e,t={}){await Yr(this.dht.provide(e,t))}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 Yr(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 new w("Not found","ERR_NOT_FOUND")}},m4=class{dht;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 new w("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}},kK=290,NK=54,LK=55,OK=56,BK=4,MK=41;function UK(r){let e=r.stringTuples();for(let t of e)if(t[0]===kK)return!1;if(e[0][0]===NK||e[0][0]===LK||e[0][0]===OK)return Ec("%m is public %s",r,!0),!0;if(e[0][0]===BK||e[0][0]===MK){let t=Nn(`${e[0][1]}`),n=t==null||!t;return Ec("%m is public %s",r,n),n}return!1}var E1=class extends Ue{wan;lan;components;contentRouting;peerRouting;constructor(e,t={}){super(),this.components=e,this.wan=new Il(e,{protocolPrefix:"/ipfs",...t,lan:!1}),this.lan=new Il(e,{protocolPrefix:"/ipfs",...t,clientMode:!1,lan:!0}),this.contentRouting=new p4(this),this.peerRouting=new m4(this),this.wan.addEventListener("peer",n=>{this.dispatchEvent(new Je("peer",{detail:n.detail}))}),this.lan.addEventListener("peer",n=>{this.dispatchEvent(new Je("peer",{detail:n.detail}))}),t.clientMode==null&&e.events.addEventListener("self:peer:update",n=>{Ec("received update of self-peer info");let i=n.detail.peer.addresses.some(({multiaddr:s})=>{let o=UK(s);return Ec("%m is public %s",s,o),o});this.getMode().then(async s=>{i&&s==="client"?await this.setMode("server"):s==="server"&&!i&&await this.setMode("client")}).catch(s=>{Ec.error("error setting dht server mode",s)})})}[Symbol.toStringTag]="@libp2p/dual-kad-dht";get[wl](){return this.contentRouting}get[bl](){return this.peerRouting}get[qo](){return this}isStarted(){return this.wan.isStarted()&&this.lan.isStarted()}async getMode(){return 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 jt(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 s of jt(this.lan.get(e,t),this.wan.get(e,t)))yield s,s.name==="DIAL_PEER"&&(n=!0),s.name==="VALUE"&&(n=!0,s.value!=null&&(i=!0)),s.name==="SEND_QUERY"&&(n=!0);if(!n)throw new w("No peers found in routing table!","ERR_NO_PEERS_IN_ROUTING_TABLE");i||(yield Br({from:this.components.peerId,error:new w("Not found","ERR_NOT_FOUND")},t))}async*provide(e,t={}){let n=0,i=0,s=[],o=[this.lan];await this.wan.getMode()==="server"&&o.push(this.wan);for await(let a of jt(...o.map(c=>c.provide(e,t))))yield a,a.name==="SEND_QUERY"&&n++,a.name==="QUERY_ERROR"&&s.push(a.error),a.name==="PEER_RESPONSE"&&a.messageName==="ADD_PROVIDER"&&(Ec("sent provider record for %s to %p",e,a.from),i++);if(i===0)throw s.length>0?new w(`Failed to provide to ${s.length} of ${n} peers`,"ERR_PROVIDES_FAILED",{errors:s}):new w("Failed to provide - no peers found","ERR_PROVIDES_FAILED")}async*findProviders(e,t={}){yield*jt(this.lan.findProviders(e,t),this.wan.findProviders(e,t))}async*findPeer(e,t={}){let n=!1;for await(let i of jt(this.lan.findPeer(e,t),this.wan.findPeer(e,t)))yield i,(i.name==="SEND_QUERY"||i.name==="FINAL_PEER")&&(n=!0);if(!n)throw new w("Peer lookup failed","ERR_LOOKUP_FAILED")}async*getClosestPeers(e,t={}){yield*jt(this.lan.getClosestPeers(e,t),this.wan.getClosestPeers(e,t))}async refreshRoutingTable(){await Promise.all([this.lan.refreshRoutingTable(),this.wan.refreshRoutingTable()])}};var h_;(function(r){r[r.SEND_QUERY=0]="SEND_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.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(h_||(h_={}));var f_;(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"})(f_||(f_={}));function d_(r){return e=>new E1(e,r)}var yS=F(D4(),1);var Te;(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"})(Te||(Te={}));var Cl=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),C4=Object.freeze({NEW_STREAM:Te.NEW_STREAM,MESSAGE:Te.MESSAGE_INITIATOR,CLOSE:Te.CLOSE_INITIATOR,RESET:Te.RESET_INITIATOR}),cS=Object.freeze({MESSAGE:Te.MESSAGE_RECEIVER,CLOSE:Te.CLOSE_RECEIVER,RESET:Te.RESET_RECEIVER});var P4=1<<20,Eq=4<<20,x1=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=P4,t=Eq){this._buffer=new j,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:s,offset:o}=this._headerInfo;if(this._buffer.length-o<s)break;let c={id:n,type:i};(i===Te.NEW_STREAM||i===Te.MESSAGE_INITIATOR||i===Te.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(o,o+s)),t.push(c),this._buffer.consume(o+s),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=lS(e),{value:i,offset:s}=lS(e,n),o=t&7;if(Cl[o]==null)throw new Error(`Invalid type received: ${o}`);if(i>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:n+s,length:i}}},vq=128,uS=127;function lS(r,e=0){let t=0,n=0,i=e,s,o=r.length;do{if(i>=o||n>49)throw e=0,new RangeError("Could not decode varint");s=r.get(i++),t+=n<28?(s&uS)<<n:(s&uS)*Math.pow(2,n),n+=7}while(s>=vq);return e=i-e,{value:t,offset:e}}function xq(r){return r[Symbol.asyncIterator]!=null}var _1=1024*1024,hS=(r,e)=>{e.append(r)};function _q(r,e){return xq(r)?async function*(){let t=new j,n=!1,i=Me(),s=Number(e?.size??_1);if((isNaN(s)||s===0||s<0)&&(s=_1),s!==Math.round(s))throw new Error("Batch size must be an integer");let o=e?.yieldAfter??0,a=e?.serialize??hS;for(Promise.resolve().then(async()=>{try{let c;for await(let u of r){if(a(u,t),t.byteLength>=s){clearTimeout(c),i.resolve();continue}c=setTimeout(()=>{i.resolve()},o)}clearTimeout(c),i.resolve()}catch(c){i.reject(c)}finally{n=!0}});!n;)if(await i.promise,i=Me(),t.byteLength>0){let c=t;t=new j,yield c.subarray()}}():function*(){let t=new j,n=Number(e?.size??_1);if((isNaN(n)||n===0||n<0)&&(n=_1),n!==Math.round(n))throw new Error("Batch size must be an integer");let i=e?.serialize??hS;for(let s of r)i(s,t),t.byteLength>=n&&(yield t.subarray(0,n),t.consume(n));t.byteLength>0&&(yield t.subarray())}()}var fS=_q;var Ac=F(bo(),1);function k4(r){return new Uint8Array(r)}var N4=10*1024,L4=class{_pool;_poolOffset;constructor(){this._pool=k4(N4),this._poolOffset=0}write(e,t){let n=this._pool,i=this._poolOffset;Ac.default.encode(e.id<<3|e.type,n,i),i+=Ac.default.encode.bytes??0,(e.type===Te.NEW_STREAM||e.type===Te.MESSAGE_INITIATOR||e.type===Te.MESSAGE_RECEIVER)&&e.data!=null?Ac.default.encode(e.data.length,n,i):Ac.default.encode(0,n,i),i+=Ac.default.encode.bytes??0;let s=n.subarray(this._poolOffset,i);N4-i<100?(this._pool=k4(N4),this._poolOffset=0):this._poolOffset=i,t.append(s),(e.type===Te.NEW_STREAM||e.type===Te.MESSAGE_INITIATOR||e.type===Te.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},dS=new L4;async function*pS(r,e=0){if(e==null||e===0){for await(let t of r){let n=new j;for(let i of t)dS.write(i,n);yield n.subarray()}return}yield*fS(r,{size:e,serialize:(t,n)=>{for(let i of t)dS.write(i,n)}})}var dn=D("libp2p:stream"),O4="ERR_STREAM_RESET",Sq="ERR_STREAM_ABORT",Aq="ERR_SINK_ENDED",Rq="ERR_DOUBLE_SINK";function Yo(r){return r!=null&&typeof r.then=="function"}var Rc=class{id;stat;metadata;source;abortController;resetController;closeController;sourceEnded;sinkEnded;sinkSunk;endErr;streamSource;onEnd;maxDataSize;constructor(e){this.abortController=new AbortController,this.resetController=new AbortController,this.closeController=new AbortController,this.sourceEnded=!1,this.sinkEnded=!1,this.sinkSunk=!1,this.id=e.id,this.metadata=e.metadata??{},this.stat={direction:e.direction,timeline:{open:Date.now()}},this.maxDataSize=e.maxDataSize,this.onEnd=e.onEnd,this.source=this.streamSource=tt({onEnd:()=>{if(this.stat.timeline.reset!==null){let t=this.sendCloseRead();Yo(t)&&t.catch(n=>{dn.error("error while sending close read",n)})}this.onSourceEnd()}}),this.sink=this.sink.bind(this)}onSourceEnd(e){this.sourceEnded||(this.stat.timeline.closeRead=Date.now(),this.sourceEnded=!0,dn.trace("%s stream %s source end - err: %o",this.stat.direction,this.id,e),e!=null&&this.endErr==null&&(this.endErr=e),this.sinkEnded&&(this.stat.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)))}onSinkEnd(e){this.sinkEnded||(this.stat.timeline.closeWrite=Date.now(),this.sinkEnded=!0,dn.trace("%s stream %s sink end - err: %o",this.stat.direction,this.id,e),e!=null&&this.endErr==null&&(this.endErr=e),this.sourceEnded&&(this.stat.timeline.close=Date.now(),this.onEnd!=null&&this.onEnd(this.endErr)))}close(){dn.trace("%s stream %s close",this.stat.direction,this.id),this.closeRead(),this.closeWrite()}closeRead(){dn.trace("%s stream %s closeRead",this.stat.direction,this.id),!this.sourceEnded&&this.streamSource.end()}closeWrite(){if(dn.trace("%s stream %s closeWrite",this.stat.direction,this.id),!this.sinkEnded){this.closeController.abort();try{let e=this.sendCloseWrite();Yo(e)&&e.catch(t=>{dn.error("error while sending close write",t)})}catch(e){dn.trace("%s stream %s error sending close",this.stat.direction,this.id,e)}this.onSinkEnd()}}abort(e){dn.trace("%s stream %s abort",this.stat.direction,this.id,e),this.streamSource.end(e),this.abortController.abort(),this.onSinkEnd(e)}reset(){let e=new w("stream reset",O4);this.resetController.abort(),this.streamSource.end(e),this.onSinkEnd(e)}async sink(e){if(this.sinkSunk)throw new w("sink already called on stream",Rq);if(this.sinkSunk=!0,this.sinkEnded)throw new w("stream closed for writing",Aq);let t=it([this.abortController.signal,this.resetController.signal,this.closeController.signal]);try{if(e=lt(e,t),this.stat.direction==="outbound"){let n=this.sendNewStream();Yo(n)&&await n}for await(let n of e)for(;n.length>0;){if(n.length<=this.maxDataSize){let s=this.sendData(n instanceof Uint8Array?new j(n):n);Yo(s)&&await s;break}n=n instanceof Uint8Array?new j(n):n;let i=this.sendData(n.sublist(0,this.maxDataSize));Yo(i)&&await i,n.consume(this.maxDataSize)}}catch(n){if(n.type==="aborted"&&n.message==="The operation was aborted"){if(this.closeController.signal.aborted)return;this.resetController.signal.aborted&&(n.message="stream reset",n.code=O4),this.abortController.signal.aborted&&(n.message="stream aborted",n.code=Sq)}if(n.code===O4)dn.trace("%s stream %s reset",this.stat.direction,this.id);else{dn.trace("%s stream %s error",this.stat.direction,this.id,n);try{let i=this.sendReset();Yo(i)&&await i,this.stat.timeline.reset=Date.now()}catch(i){dn.trace("%s stream %s error sending reset",this.stat.direction,this.id,i)}}throw this.streamSource.end(n),this.onSinkEnd(n),n}finally{t.clear()}try{let n=this.sendCloseWrite();Yo(n)&&await n}catch(n){dn.trace("%s stream %s error sending close",this.stat.direction,this.id,n)}this.onSinkEnd()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var B4=class extends Rc{name;streamId;send;types;constructor(e){super(e),this.types=e.direction==="outbound"?C4:cS,this.send=e.send,this.name=e.name,this.streamId=e.streamId}sendNewStream(){this.send({id:this.streamId,type:C4.NEW_STREAM,data:new j(q(this.name))})}sendData(e){this.send({id:this.streamId,type:this.types.MESSAGE,data:e})}sendReset(){this.send({id:this.streamId,type:this.types.RESET})}sendCloseWrite(){this.send({id:this.streamId,type:this.types.CLOSE})}sendCloseRead(){}};function mS(r){let{id:e,name:t,send:n,onEnd:i,type:s="initiator",maxMsgSize:o=P4}=r;return new B4({id:s==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:s==="initiator"?"outbound":"inbound",maxDataSize:o,onEnd:i,send:n})}var oi=D("libp2p:mplex"),Iq=1024,Tq=1024,Dq=1024*1024*4,Cq=5;function gS(r){let e={...r,type:`${Cl[r.type]} (${r.type})`};return r.type===Te.NEW_STREAM&&(e.data=B(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===Te.MESSAGE_INITIATOR||r.type===Te.MESSAGE_RECEIVER)&&(e.data=B(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var S1=class{protocol="/mplex/6.7.0";sink;source;_streamId;_streams;_init;_source;closeController;rateLimiter;constructor(e){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 yS.RateLimiterMemory({points:e.disconnectThreshold??Cq,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:s}=e;if(oi("new %s stream %s",i,t),i==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Tq))throw new w("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${i} stream ${t} already exists!`);let c=mS({id:t,name:n,send:u=>{oi.enabled&&oi.trace("%s stream %s send",i,t,gS(u)),this._source.push(u)},type:i,onEnd:()=>{oi("%s stream with id %s and protocol %s ended",i,t,c.stat.protocol),s.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return s.set(t,c),c}_createSink(){return async t=>{let n=it([this.closeController.signal,this._init.signal]);try{t=lt(t,n);let i=new x1(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let s of t)for(let o of i.write(s))await this._handleIncoming(o);this._source.end()}catch(i){oi("error in sink",i),this._source.end(i)}finally{n.clear()}}}_createSource(){let t=A6({objectMode:!0,onEnd:n=>{this.close(n)}});return Object.assign(pS(t,this._init.minSendBytes),{push:t.push,end:t.end,return:t.return})}async _handleIncoming(e){let{id:t,type:n}=e;if(oi.enabled&&oi.trace("incoming message",gS(e)),e.type===Te.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??Iq)){oi("too many inbound streams open"),this._source.push({id:t,type:Te.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{oi("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:B(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let s=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(s==null){oi("missing stream %s for message type %s",t,Cl[n]);return}let o=this._init.maxStreamBufferSize??Dq;switch(n){case Te.MESSAGE_INITIATOR:case Te.MESSAGE_RECEIVER:if(s.sourceReadableLength()>o){this._source.push({id:e.id,type:n===Te.MESSAGE_INITIATOR?Te.RESET_RECEIVER:Te.RESET_INITIATOR});let a=new w("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");s.abort(a);return}s.sourcePush(e.data);break;case Te.CLOSE_INITIATOR:case Te.CLOSE_RECEIVER:s.closeRead();break;case Te.RESET_INITIATOR:case Te.RESET_RECEIVER:s.reset();break;default:oi("unknown message type %s",n)}}};var M4=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}createStreamMuxer(e={}){return new S1({...e,...this._init})}};function wS(r={}){return()=>new M4(r)}var Pi=Symbol.for("@libp2p/transport");var no;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(no||(no={}));var pn;(function(r){r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",r.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",r.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(pn||(pn={}));var io=class extends w{constructor(e,t){super(`WebRTC transport error: ${e}`,t??""),this.name="WebRTCTransportError"}};var U4=class extends io{constructor(e,t){super(`[stream: ${e}] data channel error: ${t}`,pn.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function H4(r,e){return new U4(r,e)}var F4=class extends io{constructor(e){super(`There was a problem with the Multiaddr which was passed in: ${e}`,pn.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function A1(r){return new F4(r)}var K4=class extends io{constructor(e){super(`There was a problem with a provided argument: ${e}`,pn.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function Pl(r){return new K4(r)}var q4=class extends io{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`,pn.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function $4(r,e){return new q4(r,e)}var V4=class extends io{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`,pn.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function bS(r){return new V4(r)}var z4=class extends io{constructor(e){super(`unsupported hash algorithm: ${e}`,pn.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function ES(r){return new z4(r)}var vS=function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))},Pq=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"}return r}();var kq=function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r}();var Nq=function(){function r(e,t,n,i){this.name=e,this.version=t,this.os=n,this.bot=i,this.type="bot-device"}return r}();var Lq=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Oq=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Bq=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Mq=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,xS=3,Uq=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Bq]],_S=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function AS(r){return r?SS(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Oq:typeof navigator<"u"?SS(navigator.userAgent):qq()}function Fq(r){return r!==""&&Uq.reduce(function(e,t){var n=t[0],i=t[1];if(e)return e;var s=i.exec(r);return!!s&&[n,s]},!1)}function SS(r){var e=Fq(r);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new Lq;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<xS&&(i=vS(vS([],i,!0),Vq(xS-i.length),!0)):i=[];var s=i.join("."),o=Kq(r),a=Mq.exec(r);return a&&a[1]?new Nq(t,s,o,a[1]):new Pq(t,s,o)}function Kq(r){for(var e=0,t=_S.length;e<t;e++){var n=_S[e],i=n[0],s=n[1],o=s.exec(r);if(o)return i}return null}function qq(){var r=typeof process<"u"&&process.version;return r?new kq(process.version.slice(1)):null}function Vq(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var RS=AS(),kl=RS!=null&&RS.name==="firefox",R1=async function*(){},I1=async r=>{};var IS=D("libp2p:webrtc:connection"),Qo=class{peerConnection;remoteAddr;timeline;metrics;source=R1();sink=I1;constructor(e){this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection,this.peerConnection.onconnectionstatechange=()=>{(this.peerConnection.connectionState==="closed"||this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed")&&(this.timeline.close=Date.now())}}async close(e){e!==void 0&&IS.error("error closing connection",e),IS.trace("closing connection"),this.timeline.close=Date.now(),this.peerConnection.close(),this.metrics?.increment({close:!0})}};var Ic=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},G4=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},TS=r=>globalThis.DOMException===void 0?new G4(r):new DOMException(r),DS=r=>{let e=r.reason===void 0?TS("This operation was aborted."):r.reason;return e instanceof Error?e:TS(e)};function W4(r,e,t,n){let i,s=new Promise((o,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){o(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(DS(c)),c.addEventListener("abort",()=>{a(DS(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{o(t())}catch(l){a(l)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new Ic(c);typeof r.cancel=="function"&&r.cancel(),a(u)},e),(async()=>{try{o(await r)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}var zq=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 Hq(r,e,t){let n,i=new Promise((s,o)=>{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}=zq(r),h=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},f=d=>{n(),o(d)};n=()=>{for(let d of a)l(d,h);for(let d of t.rejectionEvents)l(d,f)};for(let d of a)u(d,h);for(let d of t.rejectionEvents)u(d,f);t.resolveImmediately&&s(c)});if(i.cancel=n,typeof t.timeout=="number"){let s=W4(i,t.timeout);return s.cancel=n,s}return i}function CS(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Hq(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}var On;(function(r){let e;(function(i){i.FIN="FIN",i.STOP_SENDING="STOP_SENDING",i.RESET="RESET"})(e=r.Flag||(r.Flag={}));let t;(function(i){i[i.FIN=0]="FIN",i[i.STOP_SENDING=1]="STOP_SENDING",i[i.RESET=2]="RESET"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.flag!=null&&(s.uint32(8),r.Flag.codec().encode(i.flag,s)),i.message!=null&&(s.uint32(18),s.bytes(i.message)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.flag=r.Flag.codec().decode(i);break;case 2:o.message=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(On||(On={}));var T1=D("libp2p:webrtc:stream"),PS=16*1024,$q=16*1024*1024,Gq=30*1e3,Wq=3,Y4=class extends Rc{channel;dataChannelOptions;incomingData;messageQueue;constructor(e){switch(super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=tt(),this.messageQueue=new j,this.dataChannelOptions={bufferedAmountLowEventTimeout:e.dataChannelOptions?.bufferedAmountLowEventTimeout??Gq,maxBufferedAmount:e.dataChannelOptions?.maxBufferedAmount??$q,maxMessageSize:e.dataChannelOptions?.maxMessageSize??PS},this.channel.readyState){case"open":break;case"closed":case"closing":(this.stat.timeline.close===void 0||this.stat.timeline.close===0)&&(this.stat.timeline.close=Date.now());break;case"connecting":break;default:throw T1.error("unknown datachannel state %s",this.channel.readyState),new w("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=n=>{this.stat.timeline.open=new Date().getTime(),this.messageQueue!=null&&(this._sendMessage(this.messageQueue).catch(i=>{this.abort(i)}),this.messageQueue=void 0)},this.channel.onclose=n=>{this.close()},this.channel.onerror=n=>{let i=n.error;this.abort(i)};let t=this;this.channel.onmessage=async n=>{let{data:i}=n;i===null||i.byteLength===0||this.incomingData.push(new Uint8Array(i,0,i.byteLength))},Promise.resolve().then(async()=>{for await(let n of Ct(this.incomingData)){let i=t.processIncomingProtobuf(n.subarray());i!=null&&t.sourcePush(new j(i))}}).catch(n=>{T1.error("error processing incoming data channel messages",n)})}sendNewStream(){}async _sendMessage(e,t=!0){if(t&&this.channel.bufferedAmount>this.dataChannelOptions.maxBufferedAmount)try{await CS(this.channel,"bufferedamountlow",{timeout:this.dataChannelOptions.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Ic?(this.abort(n),new Error("Timed out waiting for DataChannel buffer to clear")):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new w("Invalid datachannel state - closed or closing","ERR_INVALID_STATE");if(this.channel.readyState==="open")for(let n of e)this.channel.send(n);else if(this.channel.readyState==="connecting")this.messageQueue==null&&(this.messageQueue=new j),this.messageQueue.append(e);else throw T1.error("unknown datachannel state %s",this.channel.readyState),new w("Unknown datachannel state","ERR_INVALID_STATE")}async sendData(e){let t=On.encode({message:e.subarray()}),n=Et.single(t);await this._sendMessage(n)}async sendReset(){await this._sendFlag(On.Flag.RESET)}async sendCloseWrite(){await this._sendFlag(On.Flag.FIN)}async sendCloseRead(){await this._sendFlag(On.Flag.STOP_SENDING)}processIncomingProtobuf(e){let t=On.decode(e);return t.flag!==void 0&&(t.flag===On.Flag.FIN&&(this.incomingData.end(),this.closeRead()),t.flag===On.Flag.RESET&&this.reset(),t.flag===On.Flag.STOP_SENDING&&this.closeWrite()),t.message}async _sendFlag(e){T1.trace("Sending flag: %s",e.toString());let t=On.encode({flag:e}),n=Et.single(t);await this._sendMessage(n,!1)}};function Tc(r){let{channel:e,direction:t,onEnd:n,dataChannelOptions:i}=r;return new Y4({id:t==="inbound"?`i${e.id}`:`r${e.id}`,direction:t,maxDataSize:(i?.maxMessageSize??PS)-Wq,dataChannelOptions:i,onEnd:n,channel:e})}var kS="/webrtc",Xo=class{protocol;peerConnection;streamBuffer=[];metrics;dataChannelOptions;constructor(e){this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??kS,this.dataChannelOptions=e.dataChannelOptions,this.peerConnection.ondatachannel=({channel:t})=>{let n=Tc({channel:t,direction:"inbound",dataChannelOptions:e.dataChannelOptions,onEnd:()=>{this.streamBuffer=this.streamBuffer.filter(i=>i.id!==n.id)}});this.streamBuffer.push(n)}}createStreamMuxer(e){return new Q4({...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.streamBuffer,protocol:this.protocol})}},Q4=class{init;streams;protocol;peerConnection;dataChannelOptions;metrics;close=()=>{};source=R1();sink=I1;constructor(e){this.init=e,this.streams=e.streams,this.peerConnection=e.peerConnection,this.protocol=e.protocol??kS,this.metrics=e.metrics,this.peerConnection.ondatachannel=({channel:n})=>{let i=Tc({channel:n,direction:"inbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(s=>s.id!==i.id),this.metrics?.increment({stream_end:!0}),e?.onStreamEnd?.(i)}});this.streams.push(i),e?.onIncomingStream!=null&&(this.metrics?.increment({incoming_stream:!0}),e.onIncomingStream(i))};let t=e?.onIncomingStream;t!=null&&this.streams.forEach(n=>{t(n)})}newStream(){let e=this.peerConnection.createDataChannel(""),t=Tc({channel:e,direction:"outbound",dataChannelOptions:this.dataChannelOptions,onEnd:()=>{this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}});return this.streams.push(t),this.metrics?.increment({outgoing_stream:!0}),t}};var mn;(function(r){let e;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.SDP_OFFER=0]="SDP_OFFER",i[i.SDP_ANSWER=1]="SDP_ANSWER",i[i.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.data!=null&&(s.uint32(18),s.string(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.data=i.string();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(mn||(mn={}));var D1=D("libp2p:webrtc:peer:util"),X4=async(r,e,t)=>{for(;;){let n=await Promise.race([r.promise,t.read()]);if(n instanceof Object){let i=n;if(i.type!==mn.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(i.data==null||i.data===""){D1.trace("end-of-candidates received");break}D1.trace("received new ICE candidate: %s",i.data);try{await e.addIceCandidate(new RTCIceCandidate(JSON.parse(i.data)))}catch(s){throw D1.error("bad candidate received: ",s),new Error("bad candidate received")}}else break}await r.promise};function j4(r,e){r[kl?"oniceconnectionstatechange":"onconnectionstatechange"]=t=>{switch(D1.trace("receiver peerConnectionState state: ",r.connectionState),kl?r.iceConnectionState:r.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new Error("RTCPeerConnection was closed"));break;default:break}}}var Yq=30*1e3,jo=D("libp2p:webrtc:peer");async function NS({rtcConfiguration:r,dataChannelOptions:e,stream:t}){let n=AbortSignal.timeout(Yq),i=_r(Er(t,n)).pb(mn),s=new RTCPeerConnection(r),o=new Xo({peerConnection:s,dataChannelOptions:e}),a=Me(),c=Me();n.onabort=()=>{a.reject()},s.onicecandidate=({candidate:d})=>{c.promise.then(()=>{i.write({type:mn.Type.ICE_CANDIDATE,data:d!=null?JSON.stringify(d.toJSON()):""})},p=>{jo.error("cannot set candidate since sending answer failed",p)})},j4(s,a);let u=await i.read();if(u.type!==mn.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${u.type??"undefined"} `);let l=new RTCSessionDescription({type:"offer",sdp:u.data});await s.setRemoteDescription(l).catch(d=>{throw jo.error("could not execute setRemoteDescription",d),new Error("Failed to set remoteDescription")});let h=await s.createAnswer().catch(d=>{throw jo.error("could not execute createAnswer",d),c.reject(d),new Error("Failed to create answer")});i.write({type:mn.Type.SDP_ANSWER,data:h.sdp}),await s.setLocalDescription(h).catch(d=>{throw jo.error("could not execute setLocalDescription",d),c.reject(d),new Error("Failed to set localDescription")}),c.resolve(),await X4(a,s,i);let f=OS(s.currentRemoteDescription?.sdp??"");return{pc:s,muxerFactory:o,remoteAddress:f}}async function LS({rtcConfiguration:r,dataChannelOptions:e,signal:t,stream:n}){let i=_r(Er(n,t)).pb(mn),s=new RTCPeerConnection(r),o=new Xo({peerConnection:s,dataChannelOptions:e}),a=Me();j4(s,a),t.onabort=a.reject;let c=s.createDataChannel("init");s.onicecandidate=({candidate:d})=>{i.write({type:mn.Type.ICE_CANDIDATE,data:d!=null?JSON.stringify(d.toJSON()):""})};let u=await s.createOffer();i.write({type:mn.Type.SDP_OFFER,data:u.sdp}),await s.setLocalDescription(u).catch(d=>{throw jo.error("could not execute setLocalDescription",d),new Error("Failed to set localDescription")});let l=await i.read();if(l.type!==mn.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");let h=new RTCSessionDescription({type:"answer",sdp:l.data});await s.setRemoteDescription(h).catch(d=>{throw jo.error("could not execute setRemoteDescription",d),new Error("Failed to set remoteDescription")}),await X4(a,s,i),c.close();let f=OS(s.currentRemoteDescription?.sdp??"");return{pc:s,muxerFactory:o,remoteAddress:f}}function OS(r){let e=r.split(`\r
|
|
64
|
+
`).filter(n=>n.startsWith("a=candidate")).pop(),t=e?.split(" ");return e==null||t==null||t.length<5?(jo("could not parse remote address from",e),"/webrtc"):`/dnsaddr/${t[4]}/${t[2]}/${t[3]}/webrtc`}var C1=class extends Ue{peerId;transportManager;constructor(e){super(),this.peerId=e.peerId,this.transportManager=e.transportManager}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(e=>e!==this).map(e=>e.getAddrs().filter(t=>ri.matches(t)).map(t=>t.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.safeDispatchEvent("close",{})}};var BS=D("libp2p:webrtc:peer"),Qq="/webrtc",Xq="/p2p-circuit",Z4="/webrtc-signaling/0.0.1",jq=X("webrtc").code,P1=class{components;init;_started=!1;constructor(e,t={}){this.components=e,this.init=t}isStarted(){return this._started}async start(){await this.components.registrar.handle(Z4,e=>{this._onProtocol(e).catch(t=>{BS.error("failed to handle incoming connect from %p",e.connection.remotePeer,t)})}),this._started=!0}async stop(){await this.components.registrar.unhandle(Z4),this._started=!1}createListener(e){return new C1(this.components)}[Symbol.toStringTag]="@libp2p/webrtc";[Pi]=!0;filter(e){return e.filter(t=>t.protoCodes().includes(jq))}splitAddr(e){let t=e.toString().split(Qq);if(t.length!==2)throw new w("webrtc protocol was not present in multiaddr",pn.ERR_INVALID_MULTIADDR);if(!t[0].includes(Xq))throw new w("p2p-circuit protocol was not present in multiaddr",pn.ERR_INVALID_MULTIADDR);let n=re(t[0]),s=re(t[1]).getPeerId();if(s==null)throw new w("destination peer id was missing",pn.ERR_INVALID_MULTIADDR);let o=n.protos().pop();if(o===void 0)throw new w("invalid multiaddr",pn.ERR_INVALID_MULTIADDR);return o.name!=="p2p"&&(n=n.encapsulate(`/p2p/${s}`)),{baseAddr:n,peerId:oe(s)}}async dial(e,t){BS.trace("dialing address: ",e);let{baseAddr:n,peerId:i}=this.splitAddr(e);if(t.signal==null){let a=new AbortController;t.signal=a.signal}let o=await(await this.components.transportManager.dial(n,t)).newStream([Z4],t);try{let{pc:a,muxerFactory:c,remoteAddress:u}=await LS({stream:o,rtcConfiguration:this.init.rtcConfiguration,dataChannelOptions:this.init.dataChannel,signal:t.signal}),l=await t.upgrader.upgradeOutbound(new Qo({peerConnection:a,timeline:{open:Date.now()},remoteAddr:re(u).encapsulate(`/p2p/${i.toString()}`)}),{skipProtection:!0,skipEncryption:!0,muxerFactory:c});return o.close(),l}catch(a){throw o.reset(),a}}async _onProtocol({connection:e,stream:t}){try{let{pc:n,muxerFactory:i,remoteAddress:s}=await NS({rtcConfiguration:this.init.rtcConfiguration,connection:e,stream:t,dataChannelOptions:this.init.dataChannel});await this.components.upgrader.upgradeInbound(new Qo({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:re(s).encapsulate(`/p2p/${e.remotePeer.toString()}`)}),{skipEncryption:!0,skipProtection:!0,muxerFactory:i})}catch(n){throw t.reset(),n}}};var hR=F(T8(),1);var sR=F(T8(),1);var D8=D("libp2p:webrtc:sdp"),C8=Object.values(En).map(r=>r.decoder).reduce((r,e)=>r.or(e));function oR(r){let e=r.getConfiguration().certificates?.at(0);if(e==null||e.getFingerprints==null){D8.trace("fetching fingerprint from local SDP");let n=r.localDescription;return n==null?void 0:iH(n.sdp)}if(D8.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let t=e.getFingerprints()[0].value;if(t==null)throw $4("","no fingerprint on local certificate");return t}var nH=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function iH(r){return r.match(nH)?.groups?.fingerprint}function sH(r){for(let e of r.protoNames())if(e.startsWith("ip"))return e.toUpperCase();return D8("Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6",r),"IP6"}function V1(r){let t=r.stringTuples().filter(n=>n[0]===N8).map(n=>n[1])[0];if(t===void 0||t==="")throw A1(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function P8(r){let e=C8.decode(r);return sR.decode(e)}function oH(r){let e=P8(V1(r)),t=k8(e.name),n=e.digest.reduce((s,o)=>s+o.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw $4(n,r.toString());return[`${t.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function k8(r){switch(r){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw ES(r)}}function aH(r,e){let{host:t,port:n}=r.toOptions(),i=sH(r),[s]=oH(r);return`v=0
|
|
65
|
+
o=- 0 0 IN ${i} ${t}
|
|
66
|
+
s=-
|
|
67
|
+
c=IN ${i} ${t}
|
|
68
|
+
t=0 0
|
|
69
|
+
a=ice-lite
|
|
70
|
+
m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
|
|
71
|
+
a=mid:0
|
|
72
|
+
a=setup:passive
|
|
73
|
+
a=ice-ufrag:${e}
|
|
74
|
+
a=ice-pwd:${e}
|
|
75
|
+
a=fingerprint:${s}
|
|
76
|
+
a=sctp-port:5000
|
|
77
|
+
a=max-message-size:100000
|
|
78
|
+
a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
79
|
+
`}function aR(r,e){return{type:"answer",sdp:aH(r,e)}}function cR(r,e){if(r.sdp===void 0)throw Pl("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
80
|
+
a=ice-ufrag:`+e+`
|
|
81
|
+
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
82
|
+
a=ice-pwd:`+e+`
|
|
83
|
+
`),r}var uR=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),lR=r=>[...Array(r)].map(()=>uR.at(Math.floor(Math.random()*uR.length))).join("");var z1=D("libp2p:webrtc:transport"),uH=1e4,lH=X("webrtc-direct").code,N8=X("certhash").code,H1=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return z1(`dialing address - ${e.toString()}`),n}createListener(e){throw bS("WebRTCTransport.createListener")}filter(e){return e.filter(hH)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Pi]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw A1("we need to have the remote's PeerId");let o=oe(s),a=P8(V1(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:k8(a.name)}),u=new RTCPeerConnection({certificates:[c]}),l=new Promise((P,M)=>{let W=u.createDataChannel("",{negotiated:!0,id:0}),ue=setTimeout(()=>{let le=`Data channel was never opened: state: ${W.readyState}`;z1.error(le),this.metrics?.dialerEvents.increment({open_error:!0}),M(H4("data",le))},uH);W.onopen=le=>{clearTimeout(ue),P(W)},W.onerror=le=>{clearTimeout(ue);let Ve=`Error opening a data channel for handshaking: ${le.target?.toString()??"not specified"}`;z1.error(Ve),this.metrics?.dialerEvents.increment({unknown_error:!0}),M(H4("data",Ve))}}),h="libp2p+webrtc+v1/"+lR(32),f=await u.createOffer(),d=cR(f,h);await u.setLocalDescription(d);let p=aR(e,h);await u.setRemoteDescription(p);let m=await l,g=this.components.peerId,y=this.generateNoisePrologue(u,a.code,e),b=O0({prologueBytes:y})(),E=Tc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),R={...E,sink:E.sink.bind(E),source:async function*(){for await(let P of E.source)for(let M of P)yield M}()},v=new Qo({peerConnection:u,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=kl?"iceconnectionstatechange":"connectionstatechange";u.addEventListener(_,()=>{switch(u.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(P=>{z1.error("error closing connection",P)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let I=new Xo({peerConnection:u,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,R,o),t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:I})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Pl("no local certificate");let i=oR(e);if(i==null)throw Pl("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=q(s,"hex"),a=hR.encode(o,t),c=C8.decode(V1(n)),u=q("libp2p-webrtc-noise:");return he([u,a,c])}};function hH(r){let e=r.protoCodes();return e.includes(lH)&&e.includes(N8)&&r.getPeerId()!=null&&!e.includes(X("p2p-circuit").code)}function fR(r){return e=>new H1(e,r)}function dR(r){return e=>new P1(e,r)}var pR=WebSocket;var wR=F(gR(),1);function yR(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var bR=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=l=>{r.removeEventListener("open",c),r.removeEventListener("error",u),l()},c=()=>{a(s)},u=l=>{a(()=>{o(l.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",u)})},t=async function*(){let s=new wR.EventIterator(({push:o,stop:a,fail:c})=>{let u=h=>{let f=null;typeof h.data=="string"&&(f=q(h.data)),yR(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},l=h=>{c(h.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 o of s)yield yR(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var ER=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var vR=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await ER(r)}catch(s){if(s.message==="socket closed")break;throw s}r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var xR=(r,e)=>{e=e??{};let t=bR(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:vR(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var CR=F(DR(),1),xH={http:"ws",https:"wss"},_H="ws",PR=(r,e)=>(0,CR.relative)(r,e,xH,_H);function kR(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=PR(r,t.toString()),i=new pR(n,e.websocket);return xR(i,e)}function NR(r){let e;try{e=X("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function LR(r){return r.some(([e,t])=>e===X("tls").code)}function gn(r,e,t){let n=OR[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let i=n(e,t);return r===X("ip6").code?`[${i}]`:i}var OR={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://${gn(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://${gn(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`${gn(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`${gn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=LR(e),n=NR(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(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=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=LR(e),n=NR(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(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`${gn(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`${gn(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`${gn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function BR(r,e){let n=re(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=X(i[0]),o=OR[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===X("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}var FR=F(UR(),1),U8=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,W1=(0,FR.default)(),Y1=U8&&!W1,KR=W1&&!U8,qR=W1&&U8,VR=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!W1,Q1=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,C2e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",zR=typeof navigator<"u"&&navigator.product==="ReactNative";function HR(){throw new Error("WebSocket Servers can not be created in the browser!")}var F8=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},K8=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},$R=r=>globalThis.DOMException===void 0?new K8(r):new DOMException(r),GR=r=>{let e=r.reason===void 0?$R("This operation was aborted."):r.reason;return e instanceof Error?e:$R(e)};function q8(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,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:h}=e;h.aborted&&u(GR(h)),h.addEventListener("abort",()=>{u(GR(h))})}let l=new F8;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}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(h){u(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var WR=D("libp2p:websockets:socket");function YR(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=lt(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&WR.error(s)}},source:t.signal!=null?lt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await q8(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();WR("timeout closing stream to %s:%s after %dms, destroying it manually",o,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 jR(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return zo.matches(t)||Js.matches(t)})}function ZR(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Js.matches(t)})}var ao=D("libp2p:websockets"),V8=class{constructor(e){this.init=e}get[Symbol.toStringTag](){return"@libp2p/websockets"}get[Pi](){return!0}async dial(e,t){ao("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=YR(n,e);ao("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return ao("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Xr;let n=e.toOptions();ao("dialing %s:%s",n.host,n.port);let i=Me(),s=u=>{ao.error("connection error:",u),i.reject(u)},o=kR(BR(e),this.init);if(o.socket.on!=null?o.socket.on("error",s):o.socket.onerror=s,t.signal==null)return await Promise.race([o.connected(),i.promise]),ao("connected %s",e),o;let a,c=new Promise((u,l)=>{if(a=()=>{l(new Xr),o.close().catch(h=>{ao.error("error closing raw socket",h)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,i.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return ao("connected %s",e),o}createListener(e){return HR({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Y1||Q1?ZR(e):jR(e)}};function JR(r={}){return()=>new V8(r)}function X1(r){return r[Symbol.asyncIterator]!=null}var j1=r=>{let e=ct.encodingLength(r),t=Tr(e);return ct.encode(r,t),j1.bytes=e,t};j1.bytes=0;function Z1(r,e){e=e??{};let t=e.lengthEncoder??j1;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return X1(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Z1.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??j1;return new j(t(r.byteLength),r)};var Uc=F(ps(),1);var IH=8,TH=1024*1024*4,ea;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ea||(ea={}));var H8=r=>{let e=ct.decode(r);return H8.bytes=ct.encodingLength(e),e};H8.bytes=0;function z8(r,e){let t=new j,n=ea.LENGTH,i=-1,s=e?.lengthDecoder??H8,o=e?.maxLengthLength??IH,a=e?.maxDataLength??TH;function*c(){for(;t.byteLength>0;){if(n===ea.LENGTH)try{if(i=s(t),i<0)throw(0,Uc.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Uc.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=ea.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw(0,Uc.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===ea.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=ea.LENGTH}}}return X1(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Uc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Uc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}z8.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return z8(n,{...e??{},onLength:s=>{t=s}})};var J1=F(ps(),1),eI=r=>ct.decode(r);eI.bytes=0;function $8(r,e={}){let t=tt();r.sink(t).catch(o=>{t.end(o)}),r.sink=async o=>{for await(let a of o)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 j,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new j:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,J1.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new j,c=e?.lengthDecoder??eI;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,J1.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,J1.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?t.push(o):t.push(o.subarray())},writeLP:o=>{s.write(Z1.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=r.source;return r.source=async function*(){yield*i,yield*o}(),r}};return s}async function*G8(...r){let e=tt({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 CH=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},tI=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),W8=r=>r!=null&&typeof r.sink=="function"&&tI(r.source),PH=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=tt({objectMode:!0});return t.then(()=>{n.end()},s=>{n.end(s)}),G8(n,async function*(){yield*r.source,n.end()}())}return r.source};function rI(r,...e){if(W8(r)){let n=r;r=()=>n.source}else if(tI(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&W8(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)W8(t[n])&&(t[n]=PH(t[n]));return CH(...t)}function nI(r){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var ed=r=>{let e=ct.encodingLength(r),t=nI(e);return ct.encode(r,t),ed.bytes=e,t};ed.bytes=0;function iI(r){r=r??{};let e=r.lengthEncoder??ed;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}iI.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ed;return new j(t(r.byteLength),r)};var Vl=F(ps(),1),kH=8,NH=1024*1024*4,ta;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ta||(ta={}));var Y8=r=>{let e=ct.decode(r);return Y8.bytes=ct.encodingLength(e),e};Y8.bytes=0;function zl(r){return async function*(t){let n=new j,i=ta.LENGTH,s=-1,o=r?.lengthDecoder??Y8,a=r?.maxLengthLength??kH,c=r?.maxDataLength??NH;for await(let u of t)for(n.append(u);n.byteLength>0;){if(i===ta.LENGTH)try{if(s=o(n),s<0)throw(0,Vl.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Vl.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=o.bytes;n.consume(l),r?.onLength!=null&&r.onLength(s),i=ta.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>a)throw(0,Vl.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(i===ta.DATA){if(n.byteLength<s)break;let l=n.sublist(0,s);n.consume(s),r?.onData!=null&&r.onData(l),yield l,i=ta.LENGTH}}if(n.byteLength>0)throw(0,Vl.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}zl.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return zl({...e??{},onLength:s=>{t=s}})(n)};var sI=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var pI=F(hI(),1),Fc=F(Am(),1),nd=F(dI(),1),Z8=F(ul(),1),mI={hashSHA256(r){return(0,nd.hash)(r)},getHKDF(r,e){let i=new pI.HKDF(nd.SHA256,e,r).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let r=Fc.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=Fc.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return Fc.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new Z8.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new Z8.ChaCha20Poly1305(n).open(e,r,t,i)}};var J8=F(ul(),1);var qH=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Kc=r=>{let e=qH(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Kc.bytes=2;var $l=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)};$l.bytes=2;function gI(r){return he([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function yI(r){return he([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function wI(r){return he([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function bI(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 EI(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 vI(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 _I(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield Kc(o.byteLength),yield o}}}function SI(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-J8.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-J8.TAG_LENGTH),{plaintext:c,valid:u}=r.decrypt(o,r.session,a);if(!u)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var ra=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=ra.code}static get code(){return"ERR_UNEXPECTED_PEER"}},hs=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=hs.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var id;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(id||(id={}));var Wl;(function(r){let e;r.codec=()=>(e==null&&(e=se((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),id.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=id.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Wl||(Wl={}));async function AI(r,e,t){let n=await zH(r,RI(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return VH(r.publicKey,n,t)}function VH(r,e,t){return Wl.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function zH(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await cn(r.privateKey)).sign(e)}async function e5(r){return await er(r.identityKey)}function t5(r){return Wl.decode(r)}function RI(r){let e=q("noise-libp2p-static-key:");return he([e,r],e.length+r.length)}async function r5(r,e,t){let n=await er(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=RI(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 kr(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Yl(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var ar=D("libp2p:noise");var Bn;sI?Bn=ar:Bn=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function II(r){Bn(`LOCAL_STATIC_PUBLIC_KEY ${B(r.publicKey,"hex")}`),Bn(`LOCAL_STATIC_PRIVATE_KEY ${B(r.privateKey,"hex")}`)}function n5(r){r?(Bn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${B(r.publicKey,"hex")}`),Bn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${B(r.privateKey,"hex")}`)):Bn("Missing local ephemeral keys.")}function TI(r){Bn(`REMOTE_STATIC_PUBLIC_KEY ${B(r,"hex")}`)}function i5(r){Bn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${B(r,"hex")}`)}function DI(r){r.cs1&&r.cs2?(Bn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${B(r.cs1.k,"hex")}`),Bn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${B(r.cs2.k,"hex")}`)):Bn("Missing cipher state.")}var HH="Cipherstate has reached maximum n, a new handshake must be performed",sd=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(HH)}};var od=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:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return pe(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,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,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 ar.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(he([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 sd}}initializeSymmetric(e){let t=q(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),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),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var ad=class extends od{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,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 s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}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,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}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 s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return Yl(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(Yl(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&&Yl(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&Yl(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:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,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:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,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:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var cd=class{constructor(e,t,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new ad(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(II(this.session.hs.s),this.isInitiator){ar.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(gI(e)),ar.trace("Stage 0 - Initiator finished sending first message."),n5(this.session.hs.e)}else{ar.trace("Stage 0 - Responder waiting to receive first message...");let e=bI((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new hs("xx handshake stage 0 validation fail");ar.trace("Stage 0 - Responder received first message."),i5(this.session.hs.re)}}async exchange(){if(this.isInitiator){ar.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=EI((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new hs("xx handshake stage 1 validation fail");ar.trace("Stage 1 - Initiator received the message."),i5(this.session.hs.re),TI(this.session.hs.rs),ar.trace("Initiator going to check remote's signature...");try{let i=t5(t);this.remotePeer=this.remotePeer||await e5(i),await r5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new ra(`Error occurred while verifying signed payload: ${s.message}`)}ar.trace("All good with the signature!")}else{ar.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(yI(e)),ar.trace("Stage 1 - Responder sent the second handshake message with signed payload."),n5(this.session.hs.e)}}async finish(){if(this.isInitiator){ar.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(wI(e)),ar.trace("Stage 2 - Initiator sent message with signed payload.")}else{ar.trace("Stage 2 - Responder waiting for third handshake message...");let e=vI((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new hs("xx handshake stage 2 validation fail");ar.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=t5(t);this.remotePeer=this.remotePeer||await e5(i),await r5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new ra(`Error occurred while verifying signed payload: ${s.message}`)}}DI(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 hs("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 CI(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 ud=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??mI,this.extensions=n,this.metrics=o?CI(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=$8(t,{lengthEncoder:Kc,lengthDecoder:$l,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=$8(t,{lengthEncoder:Kc,lengthDecoder:$l,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await AI(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new cd(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=l0(),s=e.unwrap();return await rI(n,_I(t,this.metrics),s,zl({lengthDecoder:$l}),SI(t,this.metrics),n),i}};function PI(r={}){return()=>new ud(r)}var $r=D("libp2p:webtransport"),$H=Object.values(En).map(r=>r.decoder).reduce((r,e)=>r.or(e));function GH(r){return Fn.decode($H.decode(r))}function kI(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function NI(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.stat.timeline.close=Date.now(),i?.(h))}let c=!1,u=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||$r.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&u&&a()})().catch(()=>{$r.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&$r.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),u=!0,c&&u&&a()}().catch(()=>{$r.error("WebTransport failed to cleanup closed stream")});let l=!1,h={id:e,abort(f){c||(s.abort(),c=!0),h.closeRead(),u=!0,a()},close(){h.closeRead(),h.closeWrite(),a()},closeRead(){u||(o.cancel().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(c=!0)}),u=!0),c&&a()},closeWrite(){c||(c=!0,s.close().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(u=!0)})),u&&a()},reset(){h.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done===!0){u=!0,c&&a();return}yield new j(f.value)}}(),sink:async function(f){if(l)throw new Error("sink already called on stream");l=!0;try{for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p)}finally{h.closeWrite()}}};return h}function WH(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case X("ip6").code:case X("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case X("ip4").code:case X("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case X("quic").code:case X("quic-v1").code:case X("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case X("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case X("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([GH(a??"")])};case X("p2p").code:return{...s,remotePeer:oe(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${X(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}function YH(r,e){return e.filter(n=>!!r.find(i=>{if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(i[s]!==n[s])return!1;return!0})).length===e.length}var s5=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[Pi]=!0;async dial(e,t){$r("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=WH(e);if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(u=>({algorithm:"sha-256",value:u.digest}))});if(a.closed.catch(u=>{$r.error("WebTransport transport closed due to:",u)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,s))throw new Error("Failed to authenticate webtransport");let c={close:async u=>{u!=null&&$r("Closing webtransport with err:",u),a.close()},remoteAddr:e,timeline:{open:Date.now()},...kI()};a.closed.catch(u=>{$r.error("WebTransport connection closed:",u),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(u){throw a.close(),u}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done===!0)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},u=PI()(),{remoteExtensions:l}=await u.secureOutbound(t,c,n);if(o.close().catch(h=>{$r.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{$r.error(`Failed to close authentication stream reader: ${h.message}`)}),!YH(l?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let s=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:u}=await a.read();if(c===!0)break;if(s.length>=n.maxInboundStreams)u.writable.close().catch(l=>{$r.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${l.message}`)}),u.readable.cancel().catch(l=>{$r.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${l.message}`)});else{let l=await NI(u,String(t++),"inbound",s,i?.onStreamEnd);s.push(l),i?.onIncomingStream?.(l)}}})().catch(()=>{$r.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:s,newStream:async a=>{let c=await e.createBidirectionalStream(),u=await NI(c,String(t++),i?.direction??"outbound",s,i?.onStreamEnd);return s.push(u),u},close:a=>{a!=null&&$r("Closing webtransport muxer with err:",a),e.close()},...kI()};try{i?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function LI(r={}){return e=>new s5(e,r)}var BT=F(Zr(),1);var JI=F(zI(),1);var ZI=F(jI(),1),uo=ZI.default;var Oe;(function(r){r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",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_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"})(Oe||(Oe={}));var fd=D("libp2p:keychain"),f$="/pkcs8/",eT="/info/",na=new WeakMap,ia={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},a5={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function fs(r){return r==null||typeof r!="string"?!1:r===(0,JI.default)(r.trim())&&r.length>0}async function at(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Li(r){return new ve(f$+r)}function lo(r){return new ve(eT+r)}var sa=class{constructor(e,t){if(this.components=e,this.init=uo(a5,t),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<ia.minKeyLength)throw new Error(`dek.keyLength must be least ${ia.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<ia.minSaltLength)throw new Error(`dek.saltLength must be least ${ia.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<ia.minIterationCount)throw new Error(`dek.iterationCount must be least ${ia.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?sl(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";na.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},a5),t=Math.ceil(ia.minSaltLength/3)*3;return e.dek.salt=B(Cn(t),"base64"),e}static get options(){return a5}async createKey(e,t,n=2048){if(!fs(e)||e==="self")throw await at(),new w("Invalid key name",Oe.ERR_INVALID_KEY_NAME);if(typeof t!="string")throw await at(),new w("Invalid key type",Oe.ERR_INVALID_KEY_TYPE);let i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w("Key name already exists",Oe.ERR_KEY_ALREADY_EXISTS);switch(t.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await at(),new w("Invalid RSA key size",Oe.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await il(t,n),c=await a.id(),u=na.get(this);if(u==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let l=u.dek,h=await a.export(l);o={name:e,id:c};let f=this.components.datastore.batch();f.put(i,q(h)),f.put(lo(e),q(JSON.stringify(o))),await f.commit()}catch(a){throw await at(),a}return o}async listKeys(){let e={prefix:eT},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(B(n.value)));return t}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new w(`Key with id '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND);return n}catch(t){throw await at(),t}}async findKeyByName(e){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=lo(e);try{let n=await this.components.datastore.get(t);return JSON.parse(B(n))}catch(n){throw await at(),fd.error(n),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!fs(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=Li(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(lo(e)),await i.commit(),n}async renameKey(e,t){if(!fs(e)||e==="self")throw await at(),new w(`Invalid old key name '${e}'`,Oe.ERR_OLD_KEY_NAME_INVALID);if(!fs(t)||t==="self")throw await at(),new w(`Invalid new key name '${t}'`,Oe.ERR_NEW_KEY_NAME_INVALID);let n=Li(e),i=Li(t),s=lo(e),o=lo(t);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${t}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse(B(u));l.name=t;let h=this.components.datastore.batch();return h.put(i,c),h.put(o,q(JSON.stringify(l))),h.delete(n),h.delete(s),await h.commit(),l}catch(c){throw await at(),c}}async exportKey(e,t){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("Password is required",Oe.ERR_PASSWORD_REQUIRED);let n=Li(e);try{let i=await this.components.datastore.get(n),s=B(i),o=na.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Xa(s,a)).export(t)}catch(i){throw await at(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await Xa(n,t);return await er(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!fs(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("PEM encoded key is required",Oe.ERR_PEM_REQUIRED);let i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Xa(t,n)}catch{throw await at(),new w("Cannot read the key, most likely the password is wrong",Oe.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=na.get(this);if(l==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let h=l.dek;t=await o.export(h)}catch(l){throw await at(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,q(t)),u.put(lo(e),q(JSON.stringify(c))),await u.commit(),c}async importPeer(e,t){try{if(!fs(e))throw new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw new w("PeerId is required",Oe.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw new w("PeerId.privKey is required",Oe.ERR_MISSING_PRIVATE_KEY);let n=await cn(t.privateKey),i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o=na.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:t.toString()},l=this.components.datastore.batch();return l.put(i,q(c)),l.put(lo(e),q(JSON.stringify(u))),await l.commit(),u}catch(n){throw await at(),n}}async getPrivateKey(e){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);try{let t=Li(e),n=await this.components.datastore.get(t);return B(n)}catch(t){throw await at(),fd.error(t),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await at(),new w(`Invalid old pass type '${typeof e}'`,Oe.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await at(),new w(`Invalid new pass type '${typeof t}'`,Oe.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await at(),new w(`Invalid pass length ${t.length}`,Oe.ERR_INVALID_PASS_LENGTH);fd("recreating keychain");let n=na.get(this);if(n==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?sl(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";na.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Li(a.name)),u=B(c),l=await Xa(u,i),h=s.toString(),f=await l.export(h),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Li(a.name),q(f)),d.put(lo(a.name),q(JSON.stringify(p))),await d.commit()}fd("keychain reconstructed")}};var c5;(function(r){let e;r.codec=()=>(e==null&&(e=se((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={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>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(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(c5||(c5={}));var dd=async()=>{let r=await il("Ed25519"),e=await d$(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function tT(r){return await er(Qa(r))}async function d$(r){return await er(Qa(r.public),Z3(r))}var rT={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Ql;(function(r){let e;r.codec=()=>(e==null&&(e=se((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)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>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(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Ql||(Ql={}));var p$,Wt=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Ql.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return pe(this.marshal(),e.marshal())}async validate(e){let t=nT(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await kr(this.peerId.publicKey).verify(t.subarray(),this.signature)}};p$=Wt;Wt.createFromProtobuf=async r=>{let e=Ql.decode(r),t=await er(e.publicKey);return new Wt({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Wt.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),s=nT(t,n,i),a=await(await cn(e.privateKey)).sign(s.subarray());return new Wt({peerId:e,payloadType:n,payload:i,signature:a})};Wt.openAndCertify=async(r,e)=>{let t=await Wt.createFromProtobuf(r);if(!await t.validate(e))throw new w("envelope signature is not valid for the given domain",rT.ERR_SIGNATURE_NOT_VALID);return t};var nT=(r,e,t)=>{let n=q(r),i=ct.encode(n.byteLength),s=ct.encode(e.length),o=ct.encode(t.length);return new j(i,n,s,e,o,t)};function iT(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 Xl;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=se((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>ie(s,n.codec()),n.decode=s=>ne(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=se((n,i,s={})=>{if(s.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 o of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>ie(n,r.codec()),r.decode=n=>ne(n,r.codec())})(Xl||(Xl={}));var sT="libp2p-peer-record",oT=Uint8Array.from([3,1]);var zt=class{constructor(e){this.domain=zt.DOMAIN,this.codec=zt.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=Xl.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof zt)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!iT(this.multiaddrs,e.multiaddrs))}};zt.createFromProtobuf=r=>{let e=Xl.decode(r),t=It(e.peerId),n=(e.addresses??[]).map(s=>re(s.multiaddr)),i=e.seq;return new zt({peerId:t,multiaddrs:n,seqNumber:i})};zt.DOMAIN=sT;zt.CODEC=oT;var lr={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var zc;(function(r){let e;(function(i){let s;i.codec=()=>(s==null&&(s=se((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>ie(o,i.codec()),i.decode=o=>ne(o,i.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let s;i.codec=()=>(s==null&&(s=se((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),md.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=md.codec().decode(o,o.uint32());break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>ie(o,i.codec()),i.decode=o=>ne(o,i.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),pd.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(pd.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(zc||(zc={}));var pd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),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)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(pd||(pd={}));var md;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.value=t.uint32();break;case 2:i.expiry=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(md||(md={}));async function Hc(r,e){let t=zc.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=await tT(kr(t.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of t.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:re(s),isCertified:o??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var u5="/peers/";function $c(r){if(!pf(r)||r.type==null)throw new w("Invalid PeerId",lr.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new ve(`${u5}${e}`)}async function aT(r,e,t){let n=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=re(i.multiaddr)),!Vo(i.multiaddr))throw new w("Multiaddr was invalid",lr.ERR_INVALID_PARAMETERS);if(!await e(r,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function yd(r,e,t,n){if(e==null)throw new w("Invalid PeerData",lr.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!pe(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",lr.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!r.equals(i.id))throw new w("peer id did not match existing peer id",lr.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=gd(h,{validate:cT})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=gd(h,{validate:uT,map:lT})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of h)d==null?a.delete(f):a.set(f,d);a=gd([...a.entries()],{validate:cT})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,p]of h)p==null?f.delete(d):f.set(d,p);c=gd([...f.entries()],{validate:uT,map:lT})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await aT(r,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function gd(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([s],[o])=>s.localeCompare(o)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function cT(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",lr.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",lr.ERR_INVALID_PARAMETERS)}function uT(r,e){if(typeof r!="string")throw new w("Tag name must be a string",lr.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",lr.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",lr.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",lr.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",lr.ERR_INVALID_PARAMETERS)}}function lT(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}var wd=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Pu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has($c(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",lr.ERR_INVALID_PARAMETERS);await this.datastore.delete($c(e))}async load(e){let t=await this.datastore.get($c(e));return Hc(e,t)}async save(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:t}of this.datastore.query({prefix:u5})){let n=e.toString().split("/")[2],i=Yt.decode(n),s=It(i);s.equals(this.peerId)||(yield Hc(s,t))}}async#e(e){try{let t=await this.datastore.get($c(e)),n=await Hc(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,i){let s=zc.encode(t);return n!=null&&pe(s,n)?{peer:await Hc(e,s),previous:i,updated:!1}:(await this.datastore.put($c(e),s),{peer:await Hc(e,s),previous:i,updated:!0})}};var ft=D("libp2p:peer-store"),bd=class{store;events;peerId;constructor(e,t={}){this.events=e.events,this.peerId=e.peerId,this.store=new wd(e,t)}async forEach(e){ft.trace("forEach await read lock");let t=await this.store.lock.readLock();ft.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{ft.trace("forEach release read lock"),t()}}async all(){ft.trace("all await read lock");let e=await this.store.lock.readLock();ft.trace("all got read lock");try{let t=[];for await(let n of this.store.all())t.push(n);return t}finally{ft.trace("all release read lock"),e()}}async delete(e){ft.trace("delete await write lock");let t=await this.store.lock.writeLock();ft.trace("delete got write lock");try{await this.store.delete(e)}finally{ft.trace("delete release write lock"),t()}}async has(e){ft.trace("has await read lock");let t=await this.store.lock.readLock();ft.trace("has got read lock");try{return await this.store.has(e)}finally{ft.trace("has release read lock"),t()}}async get(e){ft.trace("get await read lock");let t=await this.store.lock.readLock();ft.trace("get got read lock");try{return await this.store.load(e)}finally{ft.trace("get release read lock"),t()}}async save(e,t){ft.trace("save await write lock");let n=await this.store.lock.writeLock();ft.trace("save got write lock");try{let i=await this.store.save(e,t);return this.#e(e,i),i.peer}finally{ft.trace("save release write lock"),n()}}async patch(e,t){ft.trace("patch await write lock");let n=await this.store.lock.writeLock();ft.trace("patch got write lock");try{let i=await this.store.patch(e,t);return this.#e(e,i),i.peer}finally{ft.trace("patch release write lock"),n()}}async merge(e,t){ft.trace("merge await write lock");let n=await this.store.lock.writeLock();ft.trace("merge got write lock");try{let i=await this.store.merge(e,t);return this.#e(e,i),i.peer}finally{ft.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Wt.openAndCertify(e,zt.DOMAIN);if(t?.equals(n.peerId)===!1)return ft("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let i=zt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await Wt.createFromProtobuf(s.peerRecordEnvelope),a=zt.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return ft("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function hT(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var m$=D("libp2p:address-manager"),g$=r=>r;function l5(r,e){let t=r.getPeerId();return t!=null&&oe(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Ed=class{components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??g$,this._updatePeerStoreAddresses=hT(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{m$.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=l5(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=l5(e,this.components.peerId);let t=e.toString(),i=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=l5(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function fT(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var h5=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>fT(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},y$=["metrics","connectionProtector"],w$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function dT(r={}){let e=new h5(r);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!w$.includes(i)){let o=e.components[i];if(o==null&&!y$.includes(i))throw new w(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}function pT(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Nn(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function f5(r){try{let{address:e}=r.nodeAddress();return!!Nn(e)}catch{return!0}}function Gc(r,e){let t=f5(r.multiaddr),n=f5(e.multiaddr);return t&&!n?1:!t&&n||r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}var p5=F(xp(),1),m5=F(yT(),1);var wT=globalThis.fetch,bT=globalThis.Headers,K8e=globalThis.Request,q8e=globalThis.Response;function vd(r,e,t){return`${r}?name=${e}&type=${t}`}async function ET(r,e){return await(await wT(r,{headers:new bT({accept:"application/dns-json"}),signal:e})).json()}function oa(r,e){return`${e}_${r}`}var d5=Object.assign((0,p5.default)("dns-over-http-resolver"),{error:(0,p5.default)("dns-over-http-resolver:error")}),g5=class{constructor(e={}){this._cache=new m5.default({max:e?.maxCache??100}),this._TXTcache=new m5.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??ET,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(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),d5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}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(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),d5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}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(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),d5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}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()}},vT=g5;var xT=vT;var{code:_$}=X("dnsaddr");async function Wc(r,e={}){let t=new xT;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,i]=r.stringTuples().find(([a])=>a===_$)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Oi;(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"})(Oi||(Oi={}));var V;(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",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(V||(V={}));var S$={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Wc},addressSorter:Gc},transportManager:{faultTolerance:no.FATAL_ALL}};function _T(r){let e=uo(S$,r);if(e.transports==null||e.transports.length<1)throw new w(Oi.ERR_TRANSPORTS_REQUIRED,V.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(Oi.ERR_PROTECTOR_REQUIRED,V.ERR_PROTECTOR_REQUIRED);return e}var ST="keep-alive";var TT=F(D4(),1);var A$=D("libp2p:get-peer");function xd(r){if(pf(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:oe(t),r.forEach(n=>{if(!Vo(n))throw A$.error("multiaddr %s was invalid",n),new w("Invalid Multiaddr",V.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}else{let s=oe(i);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Bi=D("libp2p:connection-manager:auto-dial"),_d={minConnections:50,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},Sd=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialInterval;started;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??_d.minConnections,this.autoDialPriority=t.autoDialPriority??_d.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??_d.autoDialInterval,this.started=!1,this.queue=new vt({concurrency:t.autoDialConcurrency??_d.autoDialConcurrency}),this.queue.addListener("error",n=>{Bi.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{Bi.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setInterval(()=>{this.autoDial().catch(e=>{Bi.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Bi.error("error while autodialing",e)})}stop(){this.queue.clear(),clearInterval(this.autoDialInterval),this.started=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),t=e.size,n=new Rr(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean));if(t>=this.minConnections){Bi.trace("have enough connections %d/%d",t,this.minConnections);return}Bi("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let i=await this.peerStore.all(),o=i.filter(u=>!(u.addresses.length===0||e.has(u.id)||n.has(u.id))).sort(()=>Math.random()>.5?1:-1),a=new Mr;for(let u of o)a.has(u.id)||a.set(u.id,[...u.tags.values()].reduce((l,h)=>l+h.value,0));let c=o.sort((u,l)=>{let h=a.get(u.id)??0,f=a.get(l.id)??0;return h>f?-1:h<f?1:0});Bi("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){Bi("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}Bi("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})}).catch(l=>{Bi.error("could not connect to peerStore stored peer",l)})}};var Yc=D("libp2p:connection-manager:connection-pruner"),AT={maxConnections:300,allow:[]},Ad=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,t={}){this.maxConnections=t.maxConnections??AT.maxConnections,this.allow=t.allow??AT.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Yc.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(Yc("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;Yc("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let i=new Mr;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,h)=>l+h.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Yc.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let h=a.stat.timeline.open,f=c.stat.timeline.open;return h<f?1:h>f?-1:0}),o=[];for(let a of s)if(Yc("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){Yc.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var _5=F(Zr(),1);var v5=F(Zr(),1);var RT=D("libp2p:connection-manager:utils");async function x5(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await I$(r,e),o=(await Promise.all(n.map(async a=>x5(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return RT("resolved %s to",r,o.map(a=>a.toString())),o}async function I$(r,e){try{return r=re(r.toString()),await r.resolve(e)}catch(t){return RT.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}function IT(...r){let e=[];for(let n of r)if(n!=null){try{(0,v5.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let t=it(e);try{(0,v5.setMaxListeners)?.(1/0,t)}catch{}return t}var Ir=D("libp2p:connection-manager:dial-queue"),jl={addressSorter:Gc,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Wc}},Rd=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,t={}){this.addressSorter=t.addressSorter??jl.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??jl.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=t.maxParallelDialsPerPeer??jl.maxParallelDialsPerPeer,this.dialTimeout=t.dialTimeout??jl.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,_5.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(t.resolvers??{}))Zm.set(n,i);this.queue=new vt({concurrency:t.maxParallelDials??jl.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{Ir.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:i}=xd(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(t.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...t,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:h})=>h.toString()).join()===l.multiaddrs.map(h=>h.toString()).join()));if(c!=null)return Ir("joining existing dial target for %p",n),o.clear(),c.promise;Ir("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:D$(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...t,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(l=>{throw Ir.error("dial failed to %s",u.multiaddrs.map(h=>h.toString()).join(", "),l),o.aborted?new w(l.message,V.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let t=it([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,_5.setMaxListeners)?.(1/0,t)}catch{}return t}async calculateMultiaddrs(e,t=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new w("Tried to dial self",V.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",V.ERR_PEER_DIAL_INTERCEPTED);if(t.length===0){Ir("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);t.push(...l.addresses),Ir("loaded multiaddrs for %p",e,t.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==V.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(t.map(async l=>{let h=await x5(l.multiaddr,n);return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat(),s=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),o=new Map;for(let l of s){let h=l.multiaddr.toString(),f=o.get(h);if(f!=null){f.isCertified=f.isCertified||l.isCertified||!1;continue}o.set(h,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(Ir("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),Ir("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new w("The dial request has no valid addresses",V.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new w("dial with more addresses than allowed",V.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(h=>{let f=h.multiaddr.getPeerId();return h.multiaddr.protos().pop()?.path===!0?h:f!==e.toString()?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new w("The connection gater denied all addresses in the dial request",V.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,t={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new vt({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{Ir.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new w("dialAction did not come with an AbortController",V.ERR_INVALID_PARAMETERS);let u=IT(c.signal,t.signal);u.addEventListener("abort",()=>{Ir("dial to %s aborted",o)});let l=Me();return await i.add(async()=>{if(u.aborted){Ir("dial to %s was aborted before reaching the head of the peer dial queue",o),l.reject(new Xr);return}await this.queue.add(async()=>{try{if(u.aborted){Ir("dial to %s was aborted before reaching the head of the dial queue",o),l.reject(new Xr);return}e.status="active";let h=await this.transportManager.dial(o,{...t,signal:u});if(c.signal.aborted){Ir("multiple dials succeeded, closing superfluous connection"),h.close().catch(f=>{Ir.error("error closing superfluous connection",f)}),l.reject(new Xr);return}n[a]=void 0,n.forEach(f=>{f!==void 0&&f.abort()}),Ir("dial to %s succeeded",o),l.resolve(h)}catch(h){Ir.error("error during dial of %s",o,h),l.reject(h)}},{...t,signal:u}).catch(h=>{l.reject(h)})},{signal:u}).catch(h=>{l.reject(h)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new w("successful dial led to empty object returned from peer dial queue",V.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function D$(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yn=D("libp2p:connection-manager"),k$=50,Qc={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0},Id=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,t={}){this.maxConnections=t.maxConnections??Qc.maxConnections;let n=t.minConnections??Qc.minConnections;if(this.maxConnections<n)throw new w("Connection Manager maxConnections must be greater than minConnections",V.ERR_INVALID_PARAMETERS);this.connections=new Mr,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(i=>re(i)),this.deny=(t.deny??[]).map(i=>re(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Qc.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new TT.RateLimiterMemory({points:t.inboundConnectionThreshold??Qc.inboundConnectionThreshold,duration:1}),this.autoDial=new Sd({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Qc.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Qc.autoDialPriority}),this.connectionPruner=new Ad({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Rd({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:t.addressSorter??Gc,maxParallelDials:t.maxParallelDials??100,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:Wc}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.stat.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let i of n.streams){let s=`${i.stat.direction} ${i.stat.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.stat.direction} ${o.stat.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let t={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);t[n]=i[s]}return t}}),this.autoDial.start(),this.started=!0,yn("started")}async afterStart(){Promise.resolve().then(async()=>{let e=[];for(let t of await this.peerStore.all())t.tags.has(ST)&&e.push(t.id);await Promise.all(e.map(async t=>{await this.openConnection(t).catch(n=>{yn.error(n)})}))}).catch(e=>{yn.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){yn.error(i)}})());yn("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),yn("stopped")}onConnect(e){this._onConnect(e).catch(t=>{yn.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==t.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new w("Not started",V.ERR_NODE_NOT_STARTED);let{peerId:n}=xd(e);if(n!=null){yn("dial %p",n);let a=this.getConnections(n);if(a.length>0)return yn("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??k$}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e){let t=this.connections.get(e)??[];await Promise.all(t.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return yn("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.maxIncomingPendingConnections)return yn("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 yn("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(yn("connection from %s refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};async function*Zl(r,e){yield*Kn(r,async t=>(await e.merge(t.id,{multiaddrs:t.multiaddrs}),t))}function Td(r){let e=new Set;return Fr(r,t=>e.has(t.id.toString())?!1:(e.add(t.id.toString()),!0))}async function*Dd(r,e=1){let t=0;for await(let n of r)t++,yield n;if(t<e)throw new w(`more peers required, seen: ${t} min: ${e}`,"NOT_FOUND")}var Cd=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new w("No content routers available",V.ERR_NO_ROUTERS_AVAILABLE);yield*be(jt(...this.routers.map(n=>n.findProviders(e,t))),n=>Zl(n,this.components.peerStore),n=>Td(n),n=>Dd(n))}async provide(e,t={}){if(this.routers.length===0)throw new w("No content routers available",V.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 new w(Oi.NOT_STARTED_YET,V.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new w(Oi.NOT_STARTED_YET,V.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var N$=D("libp2p:peer-routing"),Pd=class{components;routers;constructor(e,t){this.components=e,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new w("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new w("Should not try to find self",V.ERR_FIND_SELF);let n=await be(jt(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){N$.error(s)}}())),i=>Fr(i,Boolean),i=>Zl(i,this.components.peerStore),async i=>si(i));if(n!=null)return n;throw new w(Oi.NOT_FOUND,V.ERR_NOT_FOUND)}async*getClosestPeers(e,t){if(this.routers.length===0)throw new w("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);yield*be(jt(...this.routers.map(n=>n.getClosestPeers(e,t))),n=>Zl(n,this.components.peerStore),n=>Td(n),n=>Dd(n))}};var I5=D("libp2p:registrar"),T5=32,D5=64,kd=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("connection:close",this._onDisconnect),this.components.events.addEventListener("connection:open",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new w(`No handler registered for protocol ${e}`,V.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 new w(`Handler already registered for protocol ${e}`,V.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=uo.bind({ignoreUndefined:!0})({maxInboundStreams:T5,maxOutboundStreams:D5},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:t})}async register(e,t){if(!Hg(t))throw I5.error("topology must be an instance of interfaces/topology"),new w("topology must be an instance of interfaces/topology",V.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.get(t.remotePeer).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(t.remotePeer)}}).catch(n=>{I5.error("could not inform topologies of disconnecting peer %p",t.remotePeer,n)})}_onConnect(e){let t=e.detail;this.components.peerStore.get(t.remotePeer).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onConnect(t.remotePeer,t)}}).catch(n=>{I5.error("could not inform topologies of connecting peer %p",t.remotePeer,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!t.protocols.includes(o)),s=t.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect(t.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(t.id)[0];u!=null&&c.onConnect(t.id,u)}}}};var aa=D("libp2p:transports"),Nd=class{components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=hi({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??no.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new w("Transport must have a valid tag",V.ERR_INVALID_KEY);if(this.transports.has(t))throw new w(`There is already a transport with the tag ${t}`,V.ERR_DUPLICATE_TRANSPORT);aa("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(aa("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),aa("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 new w(`No transport available for address ${String(e)}`,V.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=V.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())}getListeners(){return Array.of(...this.listeners.values()).flat()}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){aa("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){aa("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),h=this.listeners.get(n)??[];h==null&&(h=[],this.listeners.set(n,h)),h.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=h.findIndex(d=>d===l);h.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){t.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==no.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,V.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===no.FATAL_ALL)throw new w(n,V.ERR_NO_VALID_ADDRESSES);aa(`libp2p in dial mode only: ${n}`)}}async remove(e){aa("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 N5=F(Zr(),1);var ds="/multistream/1.0.0";var O$=D("libp2p:mss"),DT=q(`
|
|
84
|
+
`);function Jl(r){let e=new j(r,DT);return Et.single(e)}function ca(r,e,t={}){let n=Jl(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function CT(r,e,t={}){let n=new j;for(let i of e)n.append(Jl(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function B$(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await r.next(t)},i=n;e?.signal!=null&&(i=lt(n,e.signal));let s=a=>{t=a},o=await be(i,a=>Ct(a,{onLength:s,maxDataLength:1024}),async a=>await si(a));if(o==null||o.length===0)throw new w("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==DT[0])throw O$.error("Invalid mss message - missing newline - %s",o.subarray()),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Xc(r,e){let t=await B$(r,e);return B(t.subarray())}function C5(r){let e=async function*(){let t=yield,n=new j;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new j;continue}for(n.append(i);n.length>=t;){let s=n.sublist(0,t);if(n.consume(t),t=yield s,t==null){n.length>0&&(t=yield n,n=new j);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 Ld(r){let e=tt(),t=C5(r.source),n=Me(),i,s=r.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var eh=D("libp2p:mss:select");async function th(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=Ld(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");eh.trace('select: write ["%s", "%s"]',ds,a);let c=q(ds),u=q(a);CT(i,[c,u],t);let l=await Xc(n,t);if(eh.trace('select: read "%s"',l),l===ds&&(l=await Xc(n,t),eh.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let h of e){eh.trace('select: write "%s"',h),ca(i,q(h),t);let f=await Xc(n,t);if(eh.trace('select: read "%s" for "%s"',f,h),f===h)return s(),{stream:o,protocol:h}}throw s(),new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var rh=D("libp2p:mss:handle");async function nh(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=Ld(r);for(;;){let a=await Xc(i,t);if(rh.trace('read "%s"',a),a===ds){rh.trace('respond with "%s" for "%s"',ds,a),ca(n,q(ds),t);continue}if(e.includes(a))return ca(n,q(a),t),rh.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){ca(n,new j(...e.map(c=>Jl(q(c)))),t),rh.trace('respond with "%s" for %s',e,a);continue}ca(n,q("na"),t),rh('respond with "na" for "%s"',a)}}var kT=Symbol.for("@libp2p/connection");var NT="OPEN",P5="CLOSING",Od="CLOSED";var U$=D("libp2p:connection"),k5=class{id;remoteAddr;remotePeer;stat;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.stat={...a,status:NT},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[kT]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.stat.status===P5)throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Od)throw new w("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===Od||this._closing)){this.stat.status=P5;try{this.streams.forEach(e=>{e.close()})}catch(e){U$.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=Od}}};function LT(r){return new k5(r)}var At=D("libp2p:upgrader");function K$(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return T5}function q$(r,e){try{let{options:t}=e.getHandler(r);return t.maxOutboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return D5}function OT(r,e,t){let n=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===r&&n++}),n}var Bd=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){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??3e4,this.events=e.events}async shouldBlockConnection(e,t,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,t))throw new w(`The multiaddr connection is blocked by gater.${n}`,V.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",V.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=it([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,N5.setMaxListeners)?.(1/0,u)}catch{}try{let l=Er(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",V.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),At("starting the inbound connection upgrade");let h=e;if(t?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(At("protecting the inbound connection"),h=await f.protect(e))}try{if(i=h,t?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(h));let f={...h,...i};await this.shouldBlockConnection(s,f,"denyInboundEncryptedConnection")}else{let f=e.remoteAddr.getPeerId();if(f==null)throw new w("inbound connection that skipped encryption must have a peer id",V.ERR_INVALID_MULTIADDR);let d=oe(f);c="native",s=d}if(o=i,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexInbound({...h,...i},this.muxers);a=f.muxerFactory,o=f.stream}}catch(f){throw At.error("Failed to upgrade inbound connection",f),f}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),At("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=oe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),At("Starting the outbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(l=await h.protect(e))}try{if(s=l,t?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let h={...l,...s};await this.shouldBlockConnection(o,h,"denyOutboundEncryptedConnection")}else{if(i==null)throw new w("Encryption was skipped but no peer id was passed",V.ERR_INVALID_PEER);c="native",o=i}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...l,...s},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw At.error("Failed to upgrade outbound connection",h),await e.close(h),h}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),At("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:g}=await nh(d,p);if(At("%s: incoming stream opened on %s",n,g),l==null)return;let y=K$(g,this.components.registrar);if(OT(g,"inbound",l)===y){let E=new w(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,V.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(E),E}d.source=m.source,d.sink=m.sink,d.stat.protocol=g,await this.components.peerStore.merge(o,{protocols:[g]}),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(p=>{At.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw new w("Stream is not multiplexed",V.ERR_MUXER_UNAVAILABLE);At("%s: starting new stream on %s",n,d);let m=await c.newStream();try{if(p.signal==null){At("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),p.signal=AbortSignal.timeout(3e4);try{(0,N5.setMaxListeners)?.(1/0,p.signal)}catch{}}let{stream:g,protocol:y}=await th(m,d,p),b=q$(y,this.components.registrar);if(OT(y,"outbound",l)===b){let R=new w(`Too many outbound protocol streams for protocol "${y}" - limit ${b}`,V.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(R),R}return await this.components.peerStore.merge(o,{protocols:[y]}),m.source=g.source,m.sink=g.sink,m.stat.protocol=y,this.components.metrics?.trackProtocolStream(m,l),m}catch(g){throw At.error("could not create new stream",g),m.stat.timeline.close==null&&m.close(),g.code!=null?g:new w(String(g),V.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{At.error(d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){At.error(p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{At.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let f=()=>{throw new w("connection is not multiplexed",V.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=LT({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:t},newStream:u??f,getStreams:()=>c!=null?c.streams:f(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());At("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await nh(e,t,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return At("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new w(String(n),V.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());At("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return At("encrypting outbound connection to %p",t),{...await o.secureOutbound(this.components.peerId,i,t),protocol:s}}catch(i){throw new w(String(i),V.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());At("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0});At("%s selected as muxer protocol",s);let o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing outbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());At("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await nh(e,n,{writeBytes:!0}),o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing inbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}};var Gr=D("libp2p"),L5=class extends Ue{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let t=new Ue,n=t.dispatchEvent.bind(t);t.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new Je(c.type,{detail:c.detail}));return u||l};try{(0,BT.setMaxListeners)?.(1/0,t)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=dT({peerId:e.peerId,events:t,datastore:e.datastore??new go,connectionGater:pT(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new bd(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Bd(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Nd(this.components,e.transportManager)),this.configureComponent("connectionManager",new Id(this.components,e.connectionManager)),this.configureComponent("registrar",new kd(this.components)),this.configureComponent("addressManager",new Ed(this.components,e.addresses));let s=sa.generateOptions();this.keychain=this.configureComponent("keyChain",new sa(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Pd(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Cd(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",h=>{this.#t(h)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){Gr.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[wl]!=null&&(Gr("registering service %s for content routing",c),a.push(l[wl])),l[bl]!=null&&(Gr("registering service %s for peer routing",c),o.push(l[bl])),l[qo]!=null&&(Gr("registering service %s for peer discovery",c),l[qo].addEventListener("peer",h=>{this.#t(h)}))}}configureComponent(e,t){return t==null&&Gr.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.#e)return;this.#e=!0,Gr("libp2p is starting"),(await this.keychain.listKeys()).find(t=>t.name==="self")==null&&(Gr("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),Gr("libp2p has started")}catch(t){throw Gr.error("An error occurred starting libp2p",t),await this.stop(),t}}async stop(){this.#e&&(Gr("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),Gr("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Rr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){Vo(e)&&(e=oe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,t={}){if(Gr("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=he([q("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,t);return kr(s),await this.peerStore.patch(e,{publicKey:s}),s}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 this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){Gr.error(new Error(V.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs,protocols:t.protocols}).catch(n=>{Gr.error(n)})}};async function MT(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new sa({datastore:e},uo(sa.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 dd()),new L5(_T(r))}async function UT(r){let e=await MT(r);return r.start!==!1&&await e.start(),e}var B5=F(Zr(),1);var FT="libp2p",KT="autonat",qT="1.0.0";var we;(function(r){let e;(function(u){u.DIAL="DIAL",u.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(u){u[u.DIAL=0]="DIAL",u[u.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(u){u.codec=()=>Ht(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(u){u.OK="OK",u.E_DIAL_ERROR="E_DIAL_ERROR",u.E_DIAL_REFUSED="E_DIAL_REFUSED",u.E_BAD_REQUEST="E_BAD_REQUEST",u.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(u){u[u.OK=0]="OK",u[u.E_DIAL_ERROR=100]="E_DIAL_ERROR",u[u.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",u[u.E_BAD_REQUEST=200]="E_BAD_REQUEST",u[u.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(u){u.codec=()=>Ht(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(o=r.Dial||(r.Dial={}));let a;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=se((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.type!=null&&(l.uint32(8),r.MessageType.codec().encode(u.type,l)),u.dial!=null&&(l.uint32(18),r.Dial.codec().encode(u.dial,l)),u.dialResponse!=null&&(l.uint32(26),r.DialResponse.codec().encode(u.dialResponse,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(u);break;case 2:h.dial=r.Dial.codec().decode(u,u.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(u,u.uint32());break;default:u.skipType(d&7);break}}return h})),c),r.encode=u=>ie(u,r.codec()),r.decode=u=>ne(u,r.codec())})(we||(we={}));var Qe=D("libp2p:autonat"),O5=4,M5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??FT}/${KT}/${qT}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Qe.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=it([AbortSignal.timeout(this.timeout)]);try{(0,B5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=Er(e.stream,t),s=this;await be(i,o=>Ct(o),async function*(o){let a=await si(o);if(a==null){Qe("No message received"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=we.decode(a)}catch(m){Qe.error("Could not decode message",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let u=c.dial;if(u==null){Qe.error("Dial was missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let l,h=u.peer;if(h==null||h.id==null){Qe.error("PeerId missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{l=It(h.id)}catch(m){Qe.error("Invalid PeerId",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Qe("Incoming request from %p",l),!e.connection.remotePeer.equals(l)){Qe("Target peer %p did not equal sending peer %p",l,e.connection.remotePeer),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>re(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Qe.trace("Request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Nn(g)??!1);return Qe.trace("Host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Qe.trace("Host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Qe.trace("Transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${l.toString()}`)),m));if(f.length===0){Qe("No valid multiaddrs for %p in message",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Qe("Dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),l);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Qe.error("Tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Qe("Success %p",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(X("p2p").code).bytes}});return}catch(y){Qe("Could not dial %p",l,y),d=y.message}finally{g!=null&&await g.close()}}yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>Et(o),e.stream)}catch(i){Qe.error(i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Qe.error(e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(Nn(o.host)??!1)});if(t.length===0){Qe("No public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,B5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Qe("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=we.encode({type:we.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await dd()).toBytes(),c={},u=[],l=async h=>{try{Qe("Asking %p to verify multiaddr",h.id);let f=await i.components.connectionManager.openConnection(h.id,{signal:n}),d=await f.newStream(this.protocol,{signal:n}),p=Er(d,n),m=await be([s],y=>Et(y),p,y=>Ct(y),async y=>si(y));if(m==null){Qe("No response received from %s",f.remotePeer);return}let g=we.decode(m);if(g.type!==we.MessageType.DIAL_RESPONSE||g.dialResponse==null){Qe("Invalid autonat response from %s",f.remotePeer);return}if(g.dialResponse.status===we.ResponseStatus.OK){let y=f.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Qe('Remote address "%s" was not IP4 or IP6?',y.host);return}if(u.includes(b)){Qe("Already have response from network segment %d - %s",b,y.host);return}u.push(b)}return g.dialResponse}catch(f){Qe.error(f)}};for await(let h of $o(Kn(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>l(f)),{concurrency:O5}))try{if(h==null)continue;let f=h.addr==null?t[0]:re(h.addr);if(Qe("Autonat response for %s is %s",f,h.status),h.status===we.ResponseStatus.E_BAD_REQUEST||h.status===we.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Qe("Peer reported %s as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===we.ResponseStatus.OK?c[d].success++:h.status===we.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===O5){Qe("%s is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===O5){Qe("%s is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Qe.error("Could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function VT(r={}){return e=>new M5(e,r)}var nD=F(Zr(),1);var Md="/libp2p/relay";var zT="circuit-relay-source",HT="circuit-relay-relay";var Ud=BigInt(131072),Mi="/libp2p/circuit/relay/0.2.0/hop",ih="/libp2p/circuit/relay/0.2.0/stop",$T=30*1e3,GT=30*1e3;var nt;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),Fd.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.reservation=Fd.codec().decode(i,i.uint32());break;case 4:o.limit=Zc.codec().decode(i,i.uint32());break;case 5:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(nt||(nt={}));var wn;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.limit=Zc.codec().decode(i,i.uint32());break;case 4:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(wn||(wn={}));var jc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(jc||(jc={}));var Fd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Fd||(Fd={}));var Zc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Zc||(Zc={}));var De;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(De||(De={}));var U5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(U5||(U5={}));(function(r){r.codec=()=>Ht(U5)})(De||(De={}));var Kd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Kd||(Kd={}));var F5=D("libp2p:circuit-relay:utils");async function*WT(r,e){for await(let t of r){let n=BigInt(t.byteLength);if(e.remaining-n<0){let i=Number(e.remaining);e.remaining=0n;try{i!==0&&(yield t.subarray(0,i))}catch(s){F5.error(s)}throw new Error("data limit exceeded")}e.remaining-=n,yield t}}var W$=(r,e,t,n)=>{function i(h){r.abort(h),e.abort(h),clearTimeout(a)}let s=new AbortController,o=it([t,s.signal]),a=setTimeout(()=>{s.abort()},n.duration),c=!1,u=!1,l={remaining:n.data};queueMicrotask(()=>{e.sink(WT(lt(r.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{F5.error("error while relaying streams src -> dst",h),i(h)}).finally(()=>{c=!0,u&&(o.clear(),clearTimeout(a))})}),queueMicrotask(()=>{r.sink(WT(lt(e.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{F5.error("error while relaying streams dst -> src",h),i(h)}).finally(()=>{u=!0,c&&(o.clear(),clearTimeout(a))})})};function YT(r,e,t,n){let i=n?.data??BigInt(Ud),s=n?.duration??12e4;W$(r,e,t,{data:i,duration:s})}async function qd(r){let e=new TextEncoder().encode(r),t=await Pe.digest(e);return ee.createV0(t)}function q5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var tD=F(JT(),1),Q$=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]),V5=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},X$=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},j$=r=>Q$.has(r),eD=r=>globalThis.DOMException===void 0?new Error(r):new DOMException(r);async function z5(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,...e};let i=tD.default.operation(e);i.attempt(async s=>{try{t(await r(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof V5)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!j$(o.message))i.stop(),n(o);else{X$(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{i.stop();let s=e.signal.reason===void 0?eD("The operation was aborted."):e.signal.reason;n(s instanceof Error?s:eD(s))},{once:!0})})}var H5=D("libp2p:circuit-relay:advert-service"),Vd=class extends Ue{contentRouting;timeout;started;bootDelay;constructor(e,t){super(),this.contentRouting=e.contentRouting,this.bootDelay=t?.bootDelay??GT,this.started=!1}isStarted(){return this.started}start(){this.started||(this.timeout=setTimeout(()=>{this._advertiseService().catch(e=>{H5.error("could not advertise service",e)})},this.bootDelay),this.started=!0)}stop(){try{clearTimeout(this.timeout)}catch{}this.started=!1}async _advertiseService(){await z5(async()=>{try{let e=await qd(Md);await this.contentRouting.provide(e),this.safeDispatchEvent("advert:success",{detail:void 0})}catch(e){if(this.safeDispatchEvent("advert:error",{detail:e}),e.code===V.ERR_NO_ROUTERS_AVAILABLE){H5.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop();return}throw H5.error("could not advertise service",e),e}})}};var zd=class{reservations=new Mr;_started=!1;interval;maxReservations;reservationClearInterval;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;constructor(e={}){this.maxReservations=e.maxReservations??15,this.reservationClearInterval=e.reservationClearInterval??3e5,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??72e5,this.defaultDurationLimit=e.defaultDurationLimit??12e4,this.defaultDataLimit=e.defaultDataLimit??Ud}isStarted(){return this._started}start(){this._started||(this._started=!0,this.interval=setInterval(()=>{let e=new Date().getTime();this.reservations.forEach((t,n)=>{t.expire.getTime()<e&&this.reservations.delete(n)})},this.reservationClearInterval))}stop(){clearInterval(this.interval)}reserve(e,t,n){if(this.reservations.size>=this.maxReservations&&!this.reservations.has(e))return{status:De.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),this.reservations.set(e,{addr:t,expire:i,limit:s}),{status:De.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}hasReservation(e){return this.reservations.has(e)}get(e){return this.reservations.get(e)}};var Jc=class{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Kd.encode({relay:this.relay.toBytes(),peer:this.peer.toBytes(),expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof Jc)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var bt=D("libp2p:circuit-relay:server"),rD=r=>r.protoCodes().includes(290),$5=class extends Ue{registrar;peerStore;addressManager;peerId;connectionManager;connectionGater;reservationStore;advertService;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;constructor(e,t={}){super(),this.registrar=e.registrar,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.connectionGater=e.connectionGater,this.started=!1,this.hopTimeout=t?.hopTimeout??$T,this.shutdownController=new AbortController,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams;try{(0,nD.setMaxListeners)?.(1/0,this.shutdownController.signal)}catch{}t.advertise!=null&&t.advertise!==!1&&(this.advertService=new Vd(e,t.advertise===!0?void 0:t.advertise),this.advertService.addEventListener("advert:success",()=>{this.safeDispatchEvent("relay:advert:success",{})}),this.advertService.addEventListener("advert:error",n=>{this.safeDispatchEvent("relay:advert:error",{detail:n.detail})})),this.reservationStore=new zd(t.reservations)}isStarted(){return this.started}async start(){this.started||(this.advertService?.start(),await this.registrar.handle(Mi,e=>{this.onHop(e).catch(t=>{bt.error(t)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams}),this.reservationStore.start(),this.started=!0)}async stop(){this.advertService?.stop(),this.reservationStore.stop(),this.shutdownController.abort(),await this.registrar.unhandle(Mi),this.started=!1}async onHop({connection:e,stream:t}){bt("received circuit v2 hop protocol stream from %s",e.remotePeer);let n=Me(),i=setTimeout(()=>{n.reject("timed out")},this.hopTimeout),s=_r(t);try{let o=await Promise.race([s.pb(nt).read(),n.promise]);if(o?.type==null)throw new Error("request was invalid, could not read from stream");bt("received",o.type),await Promise.race([this.handleHopProtocol({connection:e,stream:s,request:o}),n.promise])}catch(o){bt.error("error while handling hop",o),s.pb(nt).write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE}),t.abort(o)}finally{clearTimeout(i)}}async handleHopProtocol({stream:e,request:t,connection:n}){switch(bt("received hop message"),t.type){case nt.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n});break;case nt.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n});break;default:bt.error("invalid hop request type %s via peer %s",t.type,n.remotePeer),e.pb(nt).write({type:nt.Type.STATUS,status:De.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,request:t,connection:n}){let i=e.pb(nt);if(bt("hop reserve request from %s",n.remotePeer),rD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}if(await this.connectionGater.denyInboundRelayReservation?.(n.remotePeer)===!0){bt.error("reservation for %p denied by connection gater",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let s=this.reservationStore.reserve(n.remotePeer,n.remoteAddr);if(s.status!==De.OK){i.write({type:nt.Type.STATUS,status:s.status});return}try{if(s.expire!=null){let o=s.expire*1e3-Date.now();await this.peerStore.merge(n.remotePeer,{tags:{[zT]:{value:1,ttl:o}}})}i.write({type:nt.Type.STATUS,status:De.OK,reservation:await this.makeReservation(n.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(n.remotePeer)?.limit}),bt("sent confirmation response to %s",n.remotePeer)}catch(o){bt.error("failed to send confirmation response to %p",n.remotePeer,o),this.reservationStore.removeReservation(n.remotePeer)}}async makeReservation(e,t){let n=[];for(let s of this.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let i=await Wt.seal(new Jc({peer:e,relay:this.peerId,expiration:Number(t)}),this.peerId);return{addrs:n,expire:t,voucher:i.marshal()}}async handleConnect({stream:e,request:t,connection:n}){let i=e.pb(nt);if(rD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}bt("hop connect request from %s",n.remotePeer);let s;try{if(t.peer==null)throw bt.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(re),s=It(t.peer.id)}catch(h){bt.error("invalid hop connect request via peer %p %s",n.remotePeer,h),i.write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE});return}if(!this.reservationStore.hasReservation(s)){bt.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,De.NO_RESERVATION),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){bt.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let o=this.connectionManager.getConnections(s);if(o.length===0){bt("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}let a=o[0],c=await this.stopHop({connection:a,request:{type:wn.Type.CONNECT,peer:{id:n.remotePeer.toBytes(),addrs:[]}}});if(c==null){bt.error("failed to open stream to destination peer %s",a?.remotePeer),i.write({type:nt.Type.STATUS,status:De.CONNECTION_FAILED});return}i.write({type:nt.Type.STATUS,status:De.OK});let u=e.unwrap();bt("connection from %p to %p established - merging streans",n.remotePeer,s);let l=this.reservationStore.get(s)?.limit;YT(u,c,this.shutdownController.signal,l)}async stopHop({connection:e,request:t}){bt("starting circuit relay v2 stop request to %s",e.remotePeer);let n=await e.newStream([ih]),i=_r(n),s=i.pb(wn);s.write(t);let o;try{o=await s.read()}catch{bt.error("error parsing stop message response from %s",e.remotePeer)}if(o==null){bt.error("could not read response from %s",e.remotePeer),n.close();return}if(o.status===De.OK)return bt("stop request to %s was successful",e.remotePeer),i.unwrap();bt("stop request failed with code %d",o.status),n.close()}get reservations(){return this.reservationStore.reservations}};function W5(r={}){return e=>new $5(e,r)}var tG=D("libp2p:stream:converter");function Y5(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:s}=t,o=async function*(){for await(let u of s)u instanceof Uint8Array?yield u:yield*u}(),a={async sink(u){e.signal!=null&&(u=lt(u,e.signal));try{await i(u),await c()}catch(l){l.type!=="aborted"&&tG(l)}},source:e.signal!=null?lt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var fo=D("libp2p:circuit-relay:discover-relays"),Hd=class extends Ue{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Mi,Es({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{fo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){fo("searching peer store for relays");let e=(await this.peerStore.all()).filter(({protocols:t})=>t.includes(Mi)).sort(()=>Math.random()-.5);for(let t of e)fo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});fo("found %d relay peers in peer store",e.length);try{fo("searching content routing for relays");let t=await qd(Md),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),fo("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}fo("found %d relay peers in content routing",n)}catch(t){fo.error("failed when finding relays on the network",t)}}};var iD=D("libp2p:circuit-relay:transport:listener"),Q5=class extends Ue{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Mr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){iD("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let s=oe(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=re(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){iD("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>re(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function sD(r){return new Q5(r)}var bn=D("libp2p:circuit-relay:transport:reservation-store"),nG=60*1e3*10,iG=60*1e3*5,sG=30*1e3,$d=class extends Ue{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Mr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.started=!1,this.reserveQueue=new vt({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){bn("not trying to use self as relay");return}bn("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(q5(n.reservation.expire)>nG){bn("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((u,l)=>(l.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){bn("already have enough discovered relays");return}let i=await this.connectionManager.openConnection(e);if(i.remoteAddr.protoNames().includes("p2p-circuit")){bn("not creating reservation over relayed connection");return}let s=await this.#e(i);bn("created reservation on relay peer %p",e);let o=q5(s.expire),a=Math.min(Math.max(o-iG,sG),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(u=>{bn.error("could not refresh reservation to relay %p",e,u)})},a);this.reservations.set(e,{timeout:c,reservation:s,type:t}),await this.peerStore.merge(e,{tags:{[HT]:{value:1,ttl:o}}}),await this.transportManager.listen([re(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){bn.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){bn("requesting reservation from %s",e.remotePeer);let t=await e.newStream(Mi),i=_r(t).pb(nt);i.write({type:nt.Type.RESERVE});let s;try{s=await i.read()}catch(a){throw bn.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(s.status===De.OK&&s.reservation!=null)return s.reservation;let o=`reservation failed with status ${s.status??"undefined"}`;throw bn.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(bn("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(bn("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var Wr=D("libp2p:circuit-relay:transport"),oG=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(re)}catch{return!1}return!0},X5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Hd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{Wr.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new $d(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{Wr.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(ih,e=>{this.onStop(e).catch(t=>{Wr.error(t)})}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(ih),this.started=!1}[Pi]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw Wr.error(p,e),new w(p,V.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=re(n[0]),s=re(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw Wr.error(p),new w(p,V.ERR_RELAYED_DIAL)}let c=oe(o),u=oe(a),l=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),l=!0);let d;try{return d=await f.newStream([Mi]),await this.connectV2({stream:d,connection:f,destinationPeer:u,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:l})}catch(p){throw Wr.error(`Circuit relay dial to destination ${u.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),l&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=_r(e),u=c.pb(nt);u.write({type:nt.Type.CONNECT,peer:{id:n.toBytes(),addrs:[re(i).bytes]}});let l=await u.read();if(l.status!==De.OK)throw new w(`failed to connect via relay with status ${l?.status?.toString()??"undefined"}`,V.ERR_HOP_REQUEST_FAILED);let h=Y5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return Wr("new outbound connection %s",h.remoteAddr),await this.upgrader.upgradeOutbound(h)}catch(c){throw Wr.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return sD({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ri.matches(t))}async onStop({connection:e,stream:t}){let n=_r(t),i=await n.readPB(wn);if(Wr("received circuit v2 stop protocol request from %s",e.remotePeer),i?.type===void 0)return;let s=n.pb(wn);if(Wr("new circuit relay v2 stop stream from %s",e.remotePeer),i.type!==wn.Type.CONNECT){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.UNEXPECTED_MESSAGE});return}if(!oG(i)){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.MALFORMED_MESSAGE});return}let o=It(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){s.write({type:wn.Type.STATUS,status:De.PERMISSION_DENIED});return}s.write({type:wn.Type.STATUS,status:De.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],u=Y5({stream:n.unwrap(),remoteAddr:a,localAddr:c});Wr("new inbound connection %s",u.remoteAddr),await this.upgrader.upgradeInbound(u),Wr("%s connection %s upgraded","inbound",u.remoteAddr)}};function j5(r={}){return e=>new X5(e,r)}var oD="0.45.1";var Z5=`js-libp2p/${oD}`;var aD="0.1.0",cD="id",uD="id/push",lD="1.0.0",hD="1.0.0";var Gd=F(Zr(),1);var po;(function(r){let e;r.codec=()=>(e==null&&(e=se((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 s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>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(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(po||(po={}));var Ur=D("libp2p:identify"),fD=1024*8,ci={protocolPrefix:"ipfs",agentVersion:Z5,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},Wd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${cD}/${lD}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${uD}/${hD}`,this.timeout=t.timeout??ci.timeout,this.maxInboundStreams=t.maxInboundStreams??ci.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ci.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??ci.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??ci.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??ci.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ci.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??ci.protocolPrefix}/${aD}`,agentVersion:t.agentVersion??ci.agentVersion},e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Ur.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Ur.error(i)})}),this.host.agentVersion===Z5&&(VR||KR?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Y1||Q1||qR||zR)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:q(this.host.agentVersion),ProtocolVersion:q(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(l=>l.decapsulateCode(X("p2p").code)),n=new zt({peerId:this.peerId,multiaddrs:t}),i=await Wt.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=B(o.metadata.get("AgentVersion")??q(this.host.agentVersion)),c=B(o.metadata.get("ProtocolVersion")??q(this.host.protocolVersion)),u=e.map(async l=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,f)}catch{}try{h=await l.newStream([this.identifyPushProtocolStr],{signal:f}),await Er(h,f).sink(be([po.encode({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c})],p=>Et(p)))}catch(d){Ur.error("could not push identify update to peer",d)}finally{h?.close()}});await Promise.all(u)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==V.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,i=it([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:i});let s=Er(n,i),o=await be([],s,a=>Ct(a,{maxDataLength:this.maxIdentifyMessageSize??fD}),async a=>si(a));if(o==null)throw new w("No data could be retrieved",V.ERR_CONNECTION_ENDED);try{return po.decode(o)}catch(a){throw new w(String(a),V.ERR_INVALID_MESSAGE)}}finally{n?.close(),i.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",V.ERR_MISSING_PUBLIC_KEY);let a=await er(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",V.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",V.ERR_INVALID_PEER);let c=aG(o);Ur("identify completed for peer %p and protocols %o",a,s),Ur("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Ur("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let u=await this.#e(e.remotePeer,n),l={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>re(h)),observedAddr:n.observedAddr==null?void 0:re(n.observedAddr),protocols:n.protocols,signedPeerRecord:u};this.events.safeDispatchEvent("peer:identify",{detail:l})}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(f=>f.decapsulateCode(X("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let f=new zt({peerId:this.peerId,multiaddrs:a});c=(await Wt.seal(f,this.peerId)).marshal().subarray()}let u=po.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(f=>f.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),l=Er(n,i),h=be([u],f=>Et(f));await l.sink(h)}catch(s){Ur.error("could not respond to identify request",s)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i=Er(n,AbortSignal.timeout(this.timeout)),o=await _r(i,{maxDataLength:this.maxIdentifyMessageSize??fD}).readPB(po);await this.#e(t.remotePeer,o)}catch(i){Ur.error("received invalid message",i);return}finally{n.close()}Ur("handled push from %p",t.remotePeer)}async#e(e,t){if(t==null)throw new Error("Message was null or undefined");if(Ur("received identify from %p",e),t.signedPeerRecord==null)return;let n=t.signedPeerRecord,i=await Wt.openAndCertify(n,zt.DOMAIN),s=zt.createFromProtobuf(i.payload);if(!s.peerId.equals(i.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(s.peerId))throw new Error("signing key does not match remote PeerId");let o;try{o=await this.peerStore.get(s.peerId)}catch(c){if(c.code!=="ERR_NOT_FOUND")throw c}Ur("received signedPeerRecord in push from %p",e);let a=o?.metadata??new Map;if(o?.peerRecordEnvelope!=null){let c=await Wt.createFromProtobuf(o.peerRecordEnvelope),u=zt.createFromProtobuf(c.payload);u.seqNumber>=s.seqNumber&&(Ur("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,s.seqNumber),s=u,n=o.peerRecordEnvelope)}return t.agentVersion!=null&&a.set("AgentVersion",q(t.agentVersion)),t.protocolVersion!=null&&a.set("ProtocolVersion",q(t.protocolVersion)),await this.peerStore.patch(s.peerId,{peerRecordEnvelope:n,protocols:t.protocols,addresses:s.multiaddrs.map(c=>({isCertified:!0,multiaddr:c})),metadata:a}),Ur("consumed signedPeerRecord sent in push from %p",e),{seq:s.seqNumber,addresses:s.multiaddrs}}};function aG(r){if(r!=null&&r.length>0)try{return re(r)}catch{}}function dD(r={}){return e=>new Wd(e,r)}async function pD(r){return UT({...r,addresses:{listen:["/webrtc"]},transports:[dR(),fR(),LI(),JR(),j5({discoverRelays:1})],connectionEncryption:[O0()],streamMuxers:[sx(),wS()],peerDiscovery:[Ex({list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt"]})],contentRouters:[Ix("https://cid.contact")],services:{identify:dD(),autoNAT:VT(),pubsub:iv(),dht:d_({clientMode:!0}),relay:W5({advertise:!0})}})}async function cG(r={}){let e=r.datastore??new go,t=r.blockstore??new su,n=r.libp2p??await pD({datastore:e,start:!1}),i=new df({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i}return oh(uG);})();
|
|
85
|
+
/*! Bundled license information:
|
|
86
|
+
|
|
87
|
+
@noble/ed25519/lib/esm/index.js:
|
|
88
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
89
|
+
|
|
90
|
+
@noble/secp256k1/lib/esm/index.js:
|
|
91
|
+
(*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
92
|
+
|
|
93
|
+
@noble/hashes/esm/utils.js:
|
|
94
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
95
|
+
|
|
96
|
+
@libp2p/webtransport/dist/src/index.js:
|
|
97
|
+
(*! TODO unclear how to add backpressure here? *)
|
|
98
|
+
*/
|
|
3
99
|
return Helia}));
|