libp2p 1.1.1-856ccd708 → 1.1.1-ddaa59a60
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 +36 -94
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +18 -18
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,62 +1,44 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var Zd=Object.create;var bo=Object.defineProperty;var Jd=Object.getOwnPropertyDescriptor;var Qd=Object.getOwnPropertyNames;var ep=Object.getPrototypeOf,tp=Object.prototype.hasOwnProperty;var rt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),be=(r,e)=>{for(var t in e)bo(r,t,{get:e[t],enumerable:!0})},Ul=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qd(e))!tp.call(r,o)&&o!==t&&bo(r,o,{get:()=>e[o],enumerable:!(n=Jd(e,o))||n.enumerable});return r};var dt=(r,e,t)=>(t=r!=null?Zd(ep(r)):{},Ul(e||!r||!r.__esModule?bo(t,"default",{value:r,enumerable:!0}):t,r)),rp=r=>Ul(bo({},"__esModule",{value:!0}),r);var Hu=rt(an=>{"use strict";var Tg="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Tg}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Ya="string",Ng=/^[0-9a-f]+$/i,kg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Lg=/^[a-zA-Z0-9-_]+$/,$o=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=kt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Je=class{static toString(e,t=!1){let n=kt.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},Ho=class r{static isHex(e){return typeof e===Ya&&Ng.test(e)}static isBase64(e){return typeof e===Ya&&kg.test(e)}static isBase64Url(e){return typeof e===Ya&&Lg.test(e)}static ToString(e,t="utf8"){let n=kt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Je.toString(n,!0);case"utf16":case"utf16be":return Je.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Je.fromString(e,!0);case"utf16":case"utf16be":return Je.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=kt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return $o.fromString(e);case"utf16":case"utf16be":return Je.fromString(e);case"utf16le":case"usc2":return Je.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return $o.toString(e);case"utf16":case"utf16be":return Je.toString(e);case"utf16le":case"usc2":return Je.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=kt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=kt.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Je.toString(e,t)}static FromUtf16String(e,t=!1){return Je.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ho.DEFAULT_UTF8_ENCODING="utf8";function Dg(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function Pg(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function Og(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}an.BufferSourceConverter=kt;an.Convert=Ho;an.assign=Dg;an.combine=Pg;an.isEqual=Og});var fc=rt((V1,Qf)=>{var mn=1e3,gn=mn*60,yn=gn*60,_r=yn*24,g0=_r*7,y0=_r*365.25;Qf.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return w0(r);if(t==="number"&&isFinite(r))return e.long?E0(r):b0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function w0(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*y0;case"weeks":case"week":case"w":return t*g0;case"days":case"day":case"d":return t*_r;case"hours":case"hour":case"hrs":case"hr":case"h":return t*yn;case"minutes":case"minute":case"mins":case"min":case"m":return t*gn;case"seconds":case"second":case"secs":case"sec":case"s":return t*mn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function b0(r){var e=Math.abs(r);return e>=_r?Math.round(r/_r)+"d":e>=yn?Math.round(r/yn)+"h":e>=gn?Math.round(r/gn)+"m":e>=mn?Math.round(r/mn)+"s":r+"ms"}function E0(r){var e=Math.abs(r);return e>=_r?Ns(r,e,_r,"day"):e>=yn?Ns(r,e,yn,"hour"):e>=gn?Ns(r,e,gn,"minute"):e>=mn?Ns(r,e,mn,"second"):r+" ms"}function Ns(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var th=rt((K1,eh)=>{function x0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=fc(),t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let p=0;p<f.length;p++)l=(l<<5)-l+f.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,p=null,h,d;function g(...m){if(!g.enabled)return;let y=g,w=Number(new Date),b=w-(l||w);y.diff=b,y.prev=l,y.curr=w,l=w,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(R,T)=>{if(R==="%%")return"%";A++;let N=t.formatters[T];if(typeof N=="function"){let q=m[A];R=N.call(y,q),m.splice(A,1),A--}return R}),t.formatArgs.call(y,m),(y.log||t.log).apply(y,m)}return g.namespace=f,g.useColors=t.useColors(),g.color=t.selectColor(f),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,d=t.enabled(f)),d),set:m=>{p=m}}),typeof t.init=="function"&&t.init(g),g}function n(f,l){let p=t(this.namespace+(typeof l>"u"?":":l)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(l=0;l<h;l++)p[l]&&(f=p[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.slice(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,p;for(l=0,p=t.skips.length;l<p;l++)if(t.skips[l].test(f))return!1;for(l=0,p=t.names.length;l<p;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack||f.message:f}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}eh.exports=x0});var hc=rt((je,ks)=>{je.formatArgs=A0;je.save=R0;je.load=I0;je.useColors=v0;je.storage=_0();je.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`."))}})();je.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 v0(){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 A0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ks.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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}je.log=console.debug||console.log||(()=>{});function R0(r){try{r?je.storage.setItem("debug",r):je.storage.removeItem("debug")}catch{}}function I0(){let r;try{r=je.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function _0(){try{return localStorage}catch{}}ks.exports=th()(je);var{formatters:S0}=ks.exports;S0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Sh=rt((MR,kc)=>{"use strict";var ly=Object.prototype.hasOwnProperty,Ve="~";function io(){}Object.create&&(io.prototype=Object.create(null),new io().__proto__||(Ve=!1));function uy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function _h(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new uy(t,n||r,o),i=Ve?Ve+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function $s(r,e){--r._eventsCount===0?r._events=new io:delete r._events[e]}function Ue(){this._events=new io,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ly.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.prototype.listeners=function(e){var t=Ve?Ve+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ue.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=Ve?Ve+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;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,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var p=c.length,h;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Ue.prototype.on=function(e,t,n){return _h(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return _h(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return $s(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&$s(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:$s(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&$s(this,t)):(this._events=new io,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=Ve;Ue.EventEmitter=Ue;typeof kc<"u"&&(kc.exports=Ue)});var Wc=rt((r_,Kh)=>{"use strict";function Vh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Sy(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 Vh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Vh(new o,t)}}Kh.exports=Sy});var Gh=rt(uo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,p;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,p=c&255,[u,f,l,p].join(".")},i=function(c){var u,f,l,p,h,d;for(u=[],l=p=0;p<=3&&c.length!==0;l=++p){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),h=d[0],f=d[1],c=c.substring(f),u.push(h)}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"),o=t("A"),e=function(c){var u,f,l,p,h;for(p=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)p=p*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")p=p*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")p=p*u+(10+t(c[l])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[p,l]},r=function(){function c(u,f){var l,p,h,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(g){throw l=g,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(g){throw l=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);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):(i(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 f,l,p;for(p=i(this.first),l=i(this.last),f=0;p<=l;)u(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),uo.ip2long=i,uo.long2ip=a,uo.Netmask=r}).call(uo)});var Xh=rt((Wh,ti)=>{(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"),o=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",i="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(s,"i"),native:new RegExp(`^(::)?(${i})?([0-9a-f]+)?(::)?(${s})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${s})?)$`,"i"),transitional:new RegExp(`^((?:${i})|(?:::)(?:${i})?)${e}\\.${e}\\.${e}\\.${e}(${s})?$`,"i")};function c(h,d){if(h.indexOf("::")!==h.lastIndexOf("::"))return null;let g=0,m=-1,y=(h.match(a.zoneIndex)||[])[0],w,b;for(y&&(y=y.substring(1),h=h.replace(/%.+$/,""));(m=h.indexOf(":",m+1))>=0;)g++;if(h.substr(0,2)==="::"&&g--,h.substr(-2,2)==="::"&&g--,g>d)return null;for(b=d-g,w=":";b--;)w+="0:";return h=h.replace("::",w),h[0]===":"&&(h=h.slice(1)),h[h.length-1]===":"&&(h=h.slice(0,-1)),d=function(){let A=h.split(":"),v=[];for(let R=0;R<A.length;R++)v.push(parseInt(A[R],16));return v}(),{parts:d,zoneId:y}}function u(h,d,g,m){if(h.length!==d.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,w;for(;m>0;){if(w=g-m,w<0&&(w=0),h[y]>>w!==d[y]>>w)return!1;m-=g,y+=1}return!0}function f(h){if(o.test(h))return parseInt(h,16);if(h[0]==="0"&&!isNaN(parseInt(h[1],10))){if(n.test(h))return parseInt(h,8);throw new Error(`ipaddr: cannot parse ${h} as octal`)}return parseInt(h,10)}function l(h,d){for(;h.length<d;)h=`0${h}`;return h}let p={};p.IPv4=function(){function h(d){if(d.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let g,m;for(g=0;g<d.length;g++)if(m=d[g],!(0<=m&&m<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=d}return h.prototype.SpecialRanges={unspecified:[[new h([0,0,0,0]),8]],broadcast:[[new h([255,255,255,255]),32]],multicast:[[new h([224,0,0,0]),4]],linkLocal:[[new h([169,254,0,0]),16]],loopback:[[new h([127,0,0,0]),8]],carrierGradeNat:[[new h([100,64,0,0]),10]],private:[[new h([10,0,0,0]),8],[new h([172,16,0,0]),12],[new h([192,168,0,0]),16]],reserved:[[new h([192,0,0,0]),24],[new h([192,0,2,0]),24],[new h([192,88,99,0]),24],[new h([198,18,0,0]),15],[new h([198,51,100,0]),24],[new h([203,0,113,0]),24],[new h([240,0,0,0]),4]]},h.prototype.kind=function(){return"ipv4"},h.prototype.match=function(d,g){let m;if(g===void 0&&(m=d,d=m[0],g=m[1]),d.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,d.octets,8,g)},h.prototype.prefixLengthFromSubnetMask=function(){let d=0,g=!1,m={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},y,w,b;for(y=3;y>=0;y-=1)if(w=this.octets[y],w in m){if(b=m[w],g&&b!==0)return null;b!==8&&(g=!0),d+=b}else return null;return 32-d},h.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},h.prototype.toByteArray=function(){return this.octets.slice(0)},h.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},h.prototype.toNormalizedString=function(){return this.toString()},h.prototype.toString=function(){return this.octets.join(".")},h}(),p.IPv4.broadcastAddressFromCIDR=function(h){try{let d=this.parseCIDR(h),g=d[0].toByteArray(),m=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],w=0;for(;w<4;)y.push(parseInt(g[w],10)|parseInt(m[w],10)^255),w++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},p.IPv4.isIPv4=function(h){return this.parser(h)!==null},p.IPv4.isValid=function(h){try{return new this(this.parser(h)),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(h){return!!(p.IPv4.isValid(h)&&h.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.networkAddressFromCIDR=function(h){let d,g,m,y,w;try{for(d=this.parseCIDR(h),m=d[0].toByteArray(),w=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],g=0;g<4;)y.push(parseInt(m[g],10)&parseInt(w[g],10)),g++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},p.IPv4.parse=function(h){let d=this.parser(h);if(d===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(d)},p.IPv4.parseCIDR=function(h){let d;if(d=h.match(/^(.+)\/(\d+)$/)){let g=parseInt(d[2]);if(g>=0&&g<=32){let m=[this.parse(d[1]),g];return Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},p.IPv4.parser=function(h){let d,g,m;if(d=h.match(t.fourOctet))return function(){let y=d.slice(1,6),w=[];for(let b=0;b<y.length;b++)g=y[b],w.push(f(g));return w}();if(d=h.match(t.longValue)){if(m=f(d[1]),m>4294967295||m<0)throw new Error("ipaddr: address outside defined range");return function(){let y=[],w;for(w=0;w<=24;w+=8)y.push(m>>w&255);return y}().reverse()}else return(d=h.match(t.twoOctet))?function(){let y=d.slice(1,4),w=[];if(m=f(y[1]),m>16777215||m<0)throw new Error("ipaddr: address outside defined range");return w.push(f(y[0])),w.push(m>>16&255),w.push(m>>8&255),w.push(m&255),w}():(d=h.match(t.threeOctet))?function(){let y=d.slice(1,5),w=[];if(m=f(y[2]),m>65535||m<0)throw new Error("ipaddr: address outside defined range");return w.push(f(y[0])),w.push(f(y[1])),w.push(m>>8&255),w.push(m&255),w}():null},p.IPv4.subnetMaskFromPrefixLength=function(h){if(h=parseInt(h),h<0||h>32)throw new Error("ipaddr: invalid IPv4 prefix length");let d=[0,0,0,0],g=0,m=Math.floor(h/8);for(;g<m;)d[g]=255,g++;return m<4&&(d[m]=Math.pow(2,h%8)-1<<8-h%8),new this(d)},p.IPv6=function(){function h(d,g){let m,y;if(d.length===16)for(this.parts=[],m=0;m<=14;m+=2)this.parts.push(d[m]<<8|d[m+1]);else if(d.length===8)this.parts=d;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(m=0;m<this.parts.length;m++)if(y=this.parts[m],!(0<=y&&y<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");g&&(this.zoneId=g)}return h.prototype.SpecialRanges={unspecified:[new h([0,0,0,0,0,0,0,0]),128],linkLocal:[new h([65152,0,0,0,0,0,0,0]),10],multicast:[new h([65280,0,0,0,0,0,0,0]),8],loopback:[new h([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new h([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new h([0,0,0,0,0,65535,0,0]),96],rfc6145:[new h([0,0,0,0,65535,0,0,0]),96],rfc6052:[new h([100,65435,0,0,0,0,0,0]),96],"6to4":[new h([8194,0,0,0,0,0,0,0]),16],teredo:[new h([8193,0,0,0,0,0,0,0]),32],reserved:[[new h([8193,3512,0,0,0,0,0,0]),32]],benchmarking:[new h([8193,2,0,0,0,0,0,0]),48],amt:[new h([8193,3,0,0,0,0,0,0]),32],as112v6:[new h([8193,4,274,0,0,0,0,0]),48],deprecated:[new h([8193,16,0,0,0,0,0,0]),28],orchid2:[new h([8193,32,0,0,0,0,0,0]),28]},h.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},h.prototype.kind=function(){return"ipv6"},h.prototype.match=function(d,g){let m;if(g===void 0&&(m=d,d=m[0],g=m[1]),d.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,d.parts,16,g)},h.prototype.prefixLengthFromSubnetMask=function(){let d=0,g=!1,m={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,w;for(let b=7;b>=0;b-=1)if(y=this.parts[b],y in m){if(w=m[y],g&&w!==0)return null;w!==16&&(g=!0),d+=w}else return null;return 128-d},h.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},h.prototype.toByteArray=function(){let d,g=[],m=this.parts;for(let y=0;y<m.length;y++)d=m[y],g.push(d>>8),g.push(d&255);return g},h.prototype.toFixedLengthString=function(){let d=function(){let m=[];for(let y=0;y<this.parts.length;y++)m.push(l(this.parts[y].toString(16),4));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),d+g},h.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let d=this.parts.slice(-2),g=d[0],m=d[1];return new p.IPv4([g>>8,g&255,m>>8,m&255])},h.prototype.toNormalizedString=function(){let d=function(){let m=[];for(let y=0;y<this.parts.length;y++)m.push(this.parts[y].toString(16));return m}.call(this).join(":"),g="";return this.zoneId&&(g=`%${this.zoneId}`),d+g},h.prototype.toRFC5952String=function(){let d=/((^|:)(0(:|$)){2,})/g,g=this.toNormalizedString(),m=0,y=-1,w;for(;w=d.exec(g);)w[0].length>y&&(m=w.index,y=w[0].length);return y<0?g:`${g.substring(0,m)}::${g.substring(m+y)}`},h.prototype.toString=function(){return this.toRFC5952String()},h}(),p.IPv6.broadcastAddressFromCIDR=function(h){try{let d=this.parseCIDR(h),g=d[0].toByteArray(),m=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],w=0;for(;w<16;)y.push(parseInt(g[w],10)|parseInt(m[w],10)^255),w++;return new this(y)}catch(d){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${d})`)}},p.IPv6.isIPv6=function(h){return this.parser(h)!==null},p.IPv6.isValid=function(h){if(typeof h=="string"&&h.indexOf(":")===-1)return!1;try{let d=this.parser(h);return new this(d.parts,d.zoneId),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(h){let d,g,m,y,w;try{for(d=this.parseCIDR(h),m=d[0].toByteArray(),w=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),y=[],g=0;g<16;)y.push(parseInt(m[g],10)&parseInt(w[g],10)),g++;return new this(y)}catch(b){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${b})`)}},p.IPv6.parse=function(h){let d=this.parser(h);if(d.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(d.parts,d.zoneId)},p.IPv6.parseCIDR=function(h){let d,g,m;if((g=h.match(/^(.+)\/(\d+)$/))&&(d=parseInt(g[2]),d>=0&&d<=128))return m=[this.parse(g[1]),d],Object.defineProperty(m,"toString",{value:function(){return this.join("/")}}),m;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},p.IPv6.parser=function(h){let d,g,m,y,w,b;if(m=h.match(a.deprecatedTransitional))return this.parser(`::ffff:${m[1]}`);if(a.native.test(h))return c(h,8);if((m=h.match(a.transitional))&&(b=m[6]||"",d=c(m[1].slice(0,-1)+b,6),d.parts)){for(w=[parseInt(m[2]),parseInt(m[3]),parseInt(m[4]),parseInt(m[5])],g=0;g<w.length;g++)if(y=w[g],!(0<=y&&y<=255))return null;return d.parts.push(w[0]<<8|w[1]),d.parts.push(w[2]<<8|w[3]),{parts:d.parts,zoneId:d.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(h){if(h=parseInt(h),h<0||h>128)throw new Error("ipaddr: invalid IPv6 prefix length");let d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],g=0,m=Math.floor(h/8);for(;g<m;)d[g]=255,g++;return m<16&&(d[m]=Math.pow(2,h%8)-1<<8-h%8),new this(d)},p.fromByteArray=function(h){let d=h.length;if(d===4)return new p.IPv4(h);if(d===16)return new p.IPv6(h);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},p.isValid=function(h){return p.IPv6.isValid(h)||p.IPv4.isValid(h)},p.parse=function(h){if(p.IPv6.isValid(h))return p.IPv6.parse(h);if(p.IPv4.isValid(h))return p.IPv4.parse(h);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},p.parseCIDR=function(h){try{return p.IPv6.parseCIDR(h)}catch{try{return p.IPv4.parseCIDR(h)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},p.process=function(h){let d=this.parse(h);return d.kind()==="ipv6"&&d.isIPv4MappedAddress()?d.toIPv4Address():d},p.subnetMatch=function(h,d,g){let m,y,w,b;g==null&&(g="unicast");for(y in d)if(Object.prototype.hasOwnProperty.call(d,y)){for(w=d[y],w[0]&&!(w[0]instanceof Array)&&(w=[w]),m=0;m<w.length;m++)if(b=w[m],h.kind()===b[0].kind()&&h.match.apply(h,b))return y}return g},typeof ti<"u"&&ti.exports?ti.exports=p:r.ipaddr=p})(Wh)});var dd=rt((J_,hd)=>{"use strict";hd.exports=fd;var Yy=fc(),fr=fd.prototype,Wy=new Date%1e9;function Xy(){return(Math.random()*1e9>>>0)+Wy++}function fd(r){r=r||{},this.id=r.id||Xy(),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)}fr.has=function(r){return r in this._lookup};fr.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};fr.meta=function(r){if(!this.has(r))return null;var e=this._lookup[r];return"meta"in e?e.meta:null};fr.set=function(r,e,t){var n=this._lookup[r],o=this._lookup[r]={key:r,value:e};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,o)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(o),this.size++),t&&("ttl"in t&&this.expire(r,t.ttl),"meta"in t&&(o.meta=t.meta),t.refresh&&(o.refresh=t.ttl)),this};fr.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};fr.expire=function(r,e){var t=e||0,n=this._lookup[r];if(!n)return this;if(typeof t=="string"&&(t=Yy(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};fr.clear=function(){for(var r=this.items.length;r--;)this.delete(this.items[r].key);return this};fr.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 wd=rt((sS,yd)=>{"use strict";yd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Rd=rt((vd,Ad)=>{"use strict";var li=wd(),{hasOwnProperty:Ed}=Object.prototype,{propertyIsEnumerable:Qy}=Object,Tn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),ew=vd,bd={concatArrays:!1,ignoreUndefined:!1},ui=r=>{let e=[];for(let t in r)Ed.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Qy.call(r,n)&&e.push(n)}return e};function Nn(r){return Array.isArray(r)?tw(r):li(r)?rw(r):r}function tw(r){let e=r.slice(0,0);return ui(r).forEach(t=>{Tn(e,t,Nn(r[t]))}),e}function rw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return ui(r).forEach(t=>{Tn(e,t,Nn(r[t]))}),e}var xd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Tn(r,o,ul(r[o],e[o],n)):Tn(r,o,Nn(e[o])))}),r),nw=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Ed.call(s,a)&&(i.push(String(a)),s===r?Tn(n,o++,s[a]):Tn(n,o++,Nn(s[a])));n=xd(n,s,ui(s).filter(a=>!i.includes(a)),t)}),n};function ul(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?nw(r,e,t):!li(e)||!li(r)?Nn(e):xd(r,e,ui(e),t)}Ad.exports=function(...r){let e=ul(Nn(bd),this!==ew&&this||{},bd),t={_:{}};for(let n of r)if(n!==void 0){if(!li(n))throw new TypeError("`"+n+"` is not an Option Object");t=ul(t,{_:n},e)}return t._}});var Lw={};be(Lw,{createLibp2p:()=>kw});var Fl=Symbol.for("@libp2p/connection");var $i=Symbol.for("@libp2p/content-routing");var Hi=Symbol.for("@libp2p/peer-discovery");var qi=Symbol.for("@libp2p/peer-id");function Eo(r){return r!=null&&!!r[qi]}var zi=Symbol.for("@libp2p/peer-routing");var Vl="keep-alive";var Kl;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Kl||(Kl={}));var Hw=Symbol.for("@libp2p/transport");var Kt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Kt||(Kt={}));var $t=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},E=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},xo=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var vo="ERR_TIMEOUT";var pr=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 o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new ji(e,t))}},Gi=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ji=globalThis.CustomEvent??Gi;var Xe=(r,...e)=>{try{[...e]}catch{}};function $l(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Ga={};be(Ga,{Ed25519PrivateKey:()=>Qt,Ed25519PublicKey:()=>on,generateKeyPair:()=>Rg,generateKeyPairFromSeed:()=>$u,unmarshalEd25519PrivateKey:()=>vg,unmarshalEd25519PublicKey:()=>Ag});var Ji={};be(Ji,{base58btc:()=>ee,base58flickr:()=>cp});var xb=new Uint8Array(0);function Hl(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}function Rt(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")}function ql(r){return new TextEncoder().encode(r)}function zl(r){return new TextDecoder().decode(r)}function np(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);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 g=0,m=0,y=0,w=d.length;y!==w&&d[y]===0;)y++,g++;for(var b=(w-y)*f+1>>>0,A=new Uint8Array(b);y!==w;){for(var v=d[y],R=0,T=b-1;(v!==0||R<m)&&T!==-1;T--,R++)v+=256*A[T]>>>0,A[T]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=R,y++}for(var N=b-m;N!==b&&A[N]===0;)N++;for(var q=c.repeat(g);N<b;++N)q+=r.charAt(A[N]);return q}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var m=0,y=0;d[g]===c;)m++,g++;for(var w=(d.length-g)*u+1>>>0,b=new Uint8Array(w);d[g];){var A=t[d.charCodeAt(g)];if(A===255)return;for(var v=0,R=w-1;(A!==0||v<y)&&R!==-1;R--,v++)A+=a*b[R]>>>0,b[R]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=v,g++}if(d[g]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var N=new Uint8Array(m+(w-T)),q=m;T!==w;)N[q++]=b[T++];return N}}}function h(d){var g=p(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:h}}var op=np,sp=op,jl=sp;var Yi=class{name;prefix;baseEncode;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")}},Wi=class{name;prefix;baseDecode;prefixCodePoint;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 Yl(this,e)}},Xi=class{decoders;constructor(e){this.decoders=e}or(e){return Yl(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Yl(r,e){return new Xi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Zi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Yi(e,t,n),this.decoder=new Wi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $r({name:r,prefix:e,encode:t,decode:n}){return new Zi(r,e,t,n)}function Ht({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=jl(t,r);return $r({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function ip(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ap(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function ne({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return $r({prefix:e,name:r,encode(o){return ap(o,n,t)},decode(o){return ip(o,n,t,r)}})}var ee=Ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cp=Ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};be(ea,{identity:()=>qt});var lp=Zl,Wl=128,up=127,fp=~up,hp=Math.pow(2,31);function Zl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hp;)e[t++]=r&255|Wl,r/=128;for(;r&fp;)e[t++]=r&255|Wl,r>>>=7;return e[t]=r|0,Zl.bytes=t-n+1,e}var dp=Qi,pp=128,Xl=127;function Qi(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Qi.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Xl)<<o:(i&Xl)*Math.pow(2,o),o+=7}while(i>=pp);return Qi.bytes=s-n,t}var mp=Math.pow(2,7),gp=Math.pow(2,14),yp=Math.pow(2,21),wp=Math.pow(2,28),bp=Math.pow(2,35),Ep=Math.pow(2,42),xp=Math.pow(2,49),vp=Math.pow(2,56),Ap=Math.pow(2,63),Rp=function(r){return r<mp?1:r<gp?2:r<yp?3:r<wp?4:r<bp?5:r<Ep?6:r<xp?7:r<vp?8:r<Ap?9:10},Ip={encode:lp,decode:dp,encodingLength:Rp},_p=Ip,Mn=_p;function Un(r,e=0){return[Mn.decode(r,e),Mn.decode.bytes]}function Hr(r,e,t=0){return Mn.encode(r,e,t),e}function qr(r){return Mn.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=qr(r),o=n+qr(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new zr(r,t,e,s)}function mr(r){let e=Rt(r),[t,n]=Un(e),[o,s]=Un(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new zr(t,o,i,e)}function Jl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hl(r.bytes,t.bytes)}}var zr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Ql=0,Sp="identity",eu=Rt;function Bp(r){return pt(Ql,eu(r))}var qt={code:Ql,name:Sp,encode:eu,digest:Bp};var na={};be(na,{sha256:()=>Re,sha512:()=>Cp});function ra({name:r,code:e,encode:t}){return new ta(r,e,t)}var ta=class{name;code;encode;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?pt(this.code,t):t.then(n=>pt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ru(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=ra({name:"sha2-256",code:18,encode:ru("SHA-256")}),Cp=ra({name:"sha2-512",code:19,encode:ru("SHA-512")});function te(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}function zt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function It(r=0){return globalThis.Buffer?.alloc!=null?zt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function Le(r=0){return globalThis.Buffer?.allocUnsafe!=null?zt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ge(r,e){if(globalThis.Buffer!=null)return zt(globalThis.Buffer.concat(r,e));e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return zt(t)}var oa={};be(oa,{base10:()=>Tp});var Tp=Ht({prefix:"9",name:"base10",alphabet:"0123456789"});var sa={};be(sa,{base16:()=>Np,base16upper:()=>kp});var Np=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kp=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ia={};be(ia,{base2:()=>Lp});var Lp=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var aa={};be(aa,{base256emoji:()=>Up});var nu=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}"),Dp=nu.reduce((r,e,t)=>(r[t]=e,r),[]),Pp=nu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Op(r){return r.reduce((e,t)=>(e+=Dp[t],e),"")}function Mp(r){let e=[];for(let t of r){let n=Pp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Up=$r({prefix:"\u{1F680}",name:"base256emoji",encode:Op,decode:Mp});var ca={};be(ca,{base32:()=>ze,base32hex:()=>$p,base32hexpad:()=>qp,base32hexpadupper:()=>zp,base32hexupper:()=>Hp,base32pad:()=>Vp,base32padupper:()=>Kp,base32upper:()=>Fp,base32z:()=>Gp});var ze=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fp=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Vp=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Kp=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$p=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hp=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qp=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zp=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gp=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var la={};be(la,{base36:()=>jp,base36upper:()=>Yp});var jp=Ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yp=Ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fa={};be(fa,{base64:()=>Gr,base64pad:()=>Wp,base64url:()=>ua,base64urlpad:()=>Xp});var Gr=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wp=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ua=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xp=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};be(ha,{base8:()=>Zp});var Zp=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var da={};be(da,{identity:()=>Jp});var Jp=$r({prefix:"\0",name:"identity",encode:r=>zl(r),decode:r=>ql(r)});var Wb=new TextEncoder,Xb=new TextDecoder;function ou(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return rm(t,pa(r),e??ee.encoder);default:return nm(t,pa(r),e??ze.encoder)}}var su=new WeakMap;function pa(r){let e=su.get(r);if(e==null){let t=new Map;return su.set(r,t),t}return e}var nt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==om)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.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=pt(e,t);return r.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 r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Jl(e.multihash,n.multihash)}toString(e){return ou(this,e)}toJSON(){return{"/":ou(this)}}link(){return this}[Symbol.toStringTag]="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 r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??iu(n,o,s.bytes))}else if(t[sm]===!0){let{version:n,multihash:o,code:s}=t,i=mr(o);return r.create(n,s,i)}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!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=iu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Rt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new zr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Un(e.subarray(t));return t+=p,l},o=n(),s=Fn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=tm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return pa(s).set(n,e),s}};function tm(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.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)]}}}function rm(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function nm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Fn=112,om=18;function iu(r,e,t){let n=qr(r),o=n+qr(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var sm=Symbol.for("@ipld/js-cid/CID");var Gt={...da,...ia,...ha,...oa,...sa,...ca,...la,...Ji,...fa,...aa},hE={...na,...ea};function cu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var au=cu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ma=cu("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=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),im={utf8:au,"utf-8":au,hex:Gt.base16,latin1:ma,ascii:ma,binary:ma,...Gt},Ro=im;function D(r,e="utf8"){let t=Ro[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zt(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function Ze(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function jr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function am(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function ga(r,...e){if(!am(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function Io(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");jr(r.outputLen),jr(r.blockLen)}function Yr(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){ga(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var _o=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function uu(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var Xr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ot=(r,e)=>r<<32-e|r>>>e,cm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!cm)throw new Error("Non little-endian hardware is not supported");var lm=async()=>{};async function fu(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await lm(),n+=s)}}function ya(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function jt(r){if(typeof r=="string"&&(r=ya(r)),!uu(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function So(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];if(!uu(o))throw new Error("Uint8Array expected");e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Wr=class{clone(){return this._cloneInto()}},um={}.toString;function hu(r,e){if(e!==void 0&&um.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Bo(r){let e=n=>r().update(jt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Zr(r=32){if(_o&&typeof _o.getRandomValues=="function")return _o.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function fm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Jr=class extends Wr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Xr(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=jt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Xr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),lu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;fm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Xr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],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:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Co=BigInt(4294967295),wa=BigInt(32);function du(r,e=!1){return e?{h:Number(r&Co),l:Number(r>>wa&Co)}:{h:Number(r>>wa&Co)|0,l:Number(r&Co)|0}}function hm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=du(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var dm=(r,e)=>BigInt(r>>>0)<<wa|BigInt(e>>>0),pm=(r,e,t)=>r>>>t,mm=(r,e,t)=>r<<32-t|e>>>t,gm=(r,e,t)=>r>>>t|e<<32-t,ym=(r,e,t)=>r<<32-t|e>>>t,wm=(r,e,t)=>r<<64-t|e>>>t-32,bm=(r,e,t)=>r>>>t-32|e<<64-t,Em=(r,e)=>e,xm=(r,e)=>r,vm=(r,e,t)=>r<<t|e>>>32-t,Am=(r,e,t)=>e<<t|r>>>32-t,Rm=(r,e,t)=>e<<t-32|r>>>64-t,Im=(r,e,t)=>r<<t-32|e>>>64-t;function _m(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Sm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Bm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Cm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Tm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Nm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),km=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Lm={fromBig:du,split:hm,toBig:dm,shrSH:pm,shrSL:mm,rotrSH:gm,rotrSL:ym,rotrBH:wm,rotrBL:bm,rotr32H:Em,rotr32L:xm,rotlSH:vm,rotlSL:Am,rotlBH:Rm,rotlBL:Im,add:_m,add3L:Sm,add3H:Bm,add4L:Cm,add4H:Tm,add5H:km,add5L:Nm},O=Lm;var[Dm,Pm]=O.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Yt=new Uint32Array(80),Wt=new Uint32Array(80),ba=class extends Jr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:p,Gh:h,Gl:d,Hh:g,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,g,m]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,g,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=p|0,this.Gh=h|0,this.Gl=d|0,this.Hh=g|0,this.Hl=m|0}process(e,t){for(let b=0;b<16;b++,t+=4)Yt[b]=e.getUint32(t),Wt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=Yt[b-15]|0,v=Wt[b-15]|0,R=O.rotrSH(A,v,1)^O.rotrSH(A,v,8)^O.shrSH(A,v,7),T=O.rotrSL(A,v,1)^O.rotrSL(A,v,8)^O.shrSL(A,v,7),N=Yt[b-2]|0,q=Wt[b-2]|0,z=O.rotrSH(N,q,19)^O.rotrBH(N,q,61)^O.shrSH(N,q,6),M=O.rotrSL(N,q,19)^O.rotrBL(N,q,61)^O.shrSL(N,q,6),le=O.add4L(T,M,Wt[b-7],Wt[b-16]),ie=O.add4H(le,R,z,Yt[b-7],Yt[b-16]);Yt[b]=ie|0,Wt[b]=le|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:p,Fh:h,Fl:d,Gh:g,Gl:m,Hh:y,Hl:w}=this;for(let b=0;b<80;b++){let A=O.rotrSH(l,p,14)^O.rotrSH(l,p,18)^O.rotrBH(l,p,41),v=O.rotrSL(l,p,14)^O.rotrSL(l,p,18)^O.rotrBL(l,p,41),R=l&h^~l&g,T=p&d^~p&m,N=O.add5L(w,v,T,Pm[b],Wt[b]),q=O.add5H(N,y,A,R,Dm[b],Yt[b]),z=N|0,M=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),le=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),ie=n&s^n&a^s&a,We=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=d|0,h=l|0,d=p|0,{h:l,l:p}=O.add(u|0,f|0,q|0,z|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let I=O.add3L(z,le,We);n=O.add3H(I,q,M,ie),o=I|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:p}=O.add(this.Eh|0,this.El|0,l|0,p|0),{h,l:d}=O.add(this.Fh|0,this.Fl|0,h|0,d|0),{h:g,l:m}=O.add(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=O.add(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,g,m,y,w)}roundClean(){Yt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Qr=Bo(()=>new ba);var No={};be(No,{bitGet:()=>$m,bitLen:()=>Km,bitMask:()=>Vn,bitSet:()=>Hm,bytesToHex:()=>St,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>va,ensureBytes:()=>oe,equalBytes:()=>Fm,hexToBytes:()=>yr,hexToNumber:()=>xa,isBytes:()=>st,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>yu,numberToVarBytesBE:()=>Um,utf8ToBytes:()=>Vm,validateObject:()=>mt});var gu=BigInt(0),To=BigInt(1),Om=BigInt(2);function st(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}var Mm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function St(r){if(!st(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=Mm[r[t]];return e}function yu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function xa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _t={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function pu(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t._A&&r<=_t._F)return r-(_t._A-10);if(r>=_t._a&&r<=_t._f)return r-(_t._a-10)}function yr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=pu(r.charCodeAt(s)),a=pu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return xa(St(r))}function Xt(r){if(!st(r))throw new Error("Uint8Array expected");return xa(St(Uint8Array.from(r).reverse()))}function Zt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Zt(r,e).reverse()}function Um(r){return yr(yu(r))}function oe(r,e,t){let n;if(typeof e=="string")try{n=yr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(st(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Ct(...r){let e=0;for(let o=0;o<r.length;o++){let s=r[o];if(!st(s))throw new Error("Uint8Array expected");e+=s.length}let t=new Uint8Array(e),n=0;for(let o=0;o<r.length;o++){let s=r[o];t.set(s,n),n+=s.length}return t}function Fm(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Vm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Km(r){let e;for(e=0;r>gu;r>>=To,e+=1);return e}function $m(r,e){return r>>BigInt(e)&To}var Hm=(r,e,t)=>r|(t?To:gu)<<BigInt(e),Vn=r=>(Om<<BigInt(r-1))-To,Ea=r=>new Uint8Array(r),mu=r=>Uint8Array.from(r);function va(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ea(r),o=Ea(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ea())=>{o=a(mu([0]),l),n=a(),l.length!==0&&(o=a(mu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,p=[];for(;l<e;){n=a();let h=n.slice();p.push(h),l+=n.length}return Ct(...p)};return(l,p)=>{i(),c(l);let h;for(;!(h=p(u()));)c();return i(),h}}var qm={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||st(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function mt(r,e,t={}){let n=(o,s,i)=>{let a=qm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ye=BigInt(0),Z=BigInt(1),br=BigInt(2),zm=BigInt(3),Aa=BigInt(4),wu=BigInt(5),bu=BigInt(8),Gm=BigInt(9),jm=BigInt(16);function X(r,e){let t=r%e;return t>=ye?t:e+t}function Ym(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===Z)return ye;let n=Z;for(;e>ye;)e&Z&&(n=n*r%t),r=r*r%t,e>>=Z;return n}function J(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function ko(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=ye,s=Z,i=Z,a=ye;for(;t!==ye;){let u=n/t,f=n%t,l=o-i*u,p=s-a*u;n=t,t=f,o=i,s=a,i=l,a=p}if(n!==Z)throw new Error("invert: does not exist");return X(o,e)}function Wm(r){let e=(r-Z)/br,t,n,o;for(t=r-Z,n=0;t%br===ye;t/=br,n++);for(o=br;o<r&&Ym(o,e,r)!==r-Z;o++);if(n===1){let i=(r+Z)/Aa;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+Z)/br;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let g=a.sqr(p);h<u&&!a.eql(g,a.ONE);h++)g=a.sqr(g);let d=a.pow(f,Z<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function Xm(r){if(r%Aa===zm){let e=(r+Z)/Aa;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%bu===wu){let e=(r-wu)/bu;return function(n,o){let s=n.mul(o,br),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,br),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%jm,Wm(r)}var Eu=(r,e)=>(X(r,e)&Z)===Z,Zm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ra(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Zm.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function Jm(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===Z)return e;let n=r.ONE,o=e;for(;t>ye;)t&Z&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Z;return n}function Qm(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Ia(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Lo(r,e,t=!1,n={}){if(r<=ye)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ia(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Xm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Vn(o),ZERO:ye,ONE:Z,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ye<=c&&c<r},is0:c=>c===ye,isOdd:c=>(c&Z)===Z,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>Jm(a,c,u),div:(c,u)=>X(c*ko(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ko(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Qm(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function xu(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function vu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function _a(r){let e=vu(r);return e+Math.ceil(e/2)}function Au(r,e,t=!1){let n=r.length,o=vu(e),s=_a(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Xt(r),a=X(i,e-Z)+Z;return t?wr(a,o):Zt(a,o)}var tg=BigInt(0),Sa=BigInt(1);function Do(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>tg;)s&Sa&&(i=i.add(a)),a=a.double(),s>>=Sa;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let p=1;p<a;p++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let d=0;d<a;d++){let g=d*c,m=Number(i&l);i>>=h,m>c&&(m-=p,i+=Sa);let y=g,w=g+Math.abs(m)-1,b=d%2!==0,A=m<0;m===0?f=f.add(t(b,s[y])):u=u.add(t(A,s[w]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Kn(r){return Ra(r.Fp),mt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ia(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var it=BigInt(0),Ge=BigInt(1),Po=BigInt(2),rg=BigInt(8),ng={zip215:!0};function og(r){let e=Kn(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Oo(r){let e=og(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Po<<BigInt(a*8)-Ge,f=t.create,l=e.uvRatio||((_,x)=>{try{return{isValid:!0,value:t.sqrt(_*t.inv(x))}}catch{return{isValid:!1,value:it}}}),p=e.adjustScalarBytes||(_=>_),h=e.domain||((_,x,B)=>{if(x.length||B)throw new Error("Contexts/pre-hash are not supported");return _}),d=_=>typeof _=="bigint"&&it<_,g=(_,x)=>d(_)&&d(x)&&_<x,m=_=>_===it||g(_,u);function y(_,x){if(g(_,x))return _;throw new Error(`Expected valid scalar < ${x}, got ${typeof _} ${_}`)}function w(_){return _===it?_:y(_,n)}let b=new Map;function A(_){if(!(_ instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(x,B,L,P){if(this.ex=x,this.ey=B,this.ez=L,this.et=P,!m(x))throw new Error("x required");if(!m(B))throw new Error("y required");if(!m(L))throw new Error("z required");if(!m(P))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(x){if(x instanceof v)throw new Error("extended point not allowed");let{x:B,y:L}=x||{};if(!m(B)||!m(L))throw new Error("invalid affine point");return new v(B,L,Ge,f(B*L))}static normalizeZ(x){let B=t.invertBatch(x.map(L=>L.ez));return x.map((L,P)=>L.toAffine(B[P])).map(v.fromAffine)}_setWindowSize(x){this._WINDOW_SIZE=x,b.delete(this)}assertValidity(){let{a:x,d:B}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:L,ey:P,ez:F,et:K}=this,Y=f(L*L),H=f(P*P),G=f(F*F),ue=f(G*G),re=f(Y*x),ve=f(G*f(re+H)),Ae=f(ue+f(B*f(Y*H)));if(ve!==Ae)throw new Error("bad point: equation left != right (1)");let me=f(L*P),ke=f(F*K);if(me!==ke)throw new Error("bad point: equation left != right (2)")}equals(x){A(x);let{ex:B,ey:L,ez:P}=this,{ex:F,ey:K,ez:Y}=x,H=f(B*Y),G=f(F*P),ue=f(L*Y),re=f(K*P);return H===G&&ue===re}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:x}=e,{ex:B,ey:L,ez:P}=this,F=f(B*B),K=f(L*L),Y=f(Po*f(P*P)),H=f(x*F),G=B+L,ue=f(f(G*G)-F-K),re=H+K,ve=re-Y,Ae=H-K,me=f(ue*ve),ke=f(re*Ae),At=f(ue*Ae),dr=f(ve*re);return new v(me,ke,dr,At)}add(x){A(x);let{a:B,d:L}=e,{ex:P,ey:F,ez:K,et:Y}=this,{ex:H,ey:G,ez:ue,et:re}=x;if(B===BigInt(-1)){let Nl=f((F-P)*(G+H)),kl=f((F+P)*(G-H)),Ki=f(kl-Nl);if(Ki===it)return this.double();let Ll=f(K*Po*re),Dl=f(Y*Po*ue),Pl=Dl+Ll,Ol=kl+Nl,Ml=Dl-Ll,jd=f(Pl*Ki),Yd=f(Ol*Ml),Wd=f(Pl*Ml),Xd=f(Ki*Ol);return new v(jd,Yd,Xd,Wd)}let ve=f(P*H),Ae=f(F*G),me=f(Y*L*re),ke=f(K*ue),At=f((P+F)*(H+G)-ve-Ae),dr=ke-me,On=ke+me,Tl=f(Ae-B*ve),Hd=f(At*dr),qd=f(On*Tl),zd=f(At*Tl),Gd=f(dr*On);return new v(Hd,qd,Gd,zd)}subtract(x){return this.add(x.negate())}wNAF(x){return N.wNAFCached(this,b,x,v.normalizeZ)}multiply(x){let{p:B,f:L}=this.wNAF(y(x,n));return v.normalizeZ([B,L])[0]}multiplyUnsafe(x){let B=w(x);return B===it?T:this.equals(T)||B===Ge?this:this.equals(R)?this.wNAF(B).p:N.unsafeLadder(this,B)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(x){let{ex:B,ey:L,ez:P}=this,F=this.is0();x==null&&(x=F?rg:t.inv(P));let K=f(B*x),Y=f(L*x),H=f(P*x);if(F)return{x:it,y:Ge};if(H!==Ge)throw new Error("invZ was invalid");return{x:K,y:Y}}clearCofactor(){let{h:x}=e;return x===Ge?this:this.multiplyUnsafe(x)}static fromHex(x,B=!1){let{d:L,a:P}=e,F=t.BYTES;x=oe("pointHex",x,F);let K=x.slice(),Y=x[F-1];K[F-1]=Y&-129;let H=Xt(K);H===it||(B?y(H,u):y(H,t.ORDER));let G=f(H*H),ue=f(G-Ge),re=f(L*G-P),{isValid:ve,value:Ae}=l(ue,re);if(!ve)throw new Error("Point.fromHex: invalid y coordinate");let me=(Ae&Ge)===Ge,ke=(Y&128)!==0;if(!B&&Ae===it&&ke)throw new Error("Point.fromHex: x=0 and x_0=1");return ke!==me&&(Ae=f(-Ae)),v.fromAffine({x:Ae,y:H})}static fromPrivateKey(x){return M(x).point}toRawBytes(){let{x,y:B}=this.toAffine(),L=wr(B,t.BYTES);return L[L.length-1]|=x&Ge?128:0,L}toHex(){return St(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ge,f(e.Gx*e.Gy)),v.ZERO=new v(it,Ge,Ge,it);let{BASE:R,ZERO:T}=v,N=Do(v,a*8);function q(_){return X(_,n)}function z(_){return q(Xt(_))}function M(_){let x=a;_=oe("private key",_,x);let B=oe("hashed private key",s(_),2*x),L=p(B.slice(0,x)),P=B.slice(x,2*x),F=z(L),K=R.multiply(F),Y=K.toRawBytes();return{head:L,prefix:P,scalar:F,point:K,pointBytes:Y}}function le(_){return M(_).pointBytes}function ie(_=new Uint8Array,...x){let B=Ct(...x);return z(s(h(B,oe("context",_),!!o)))}function We(_,x,B={}){_=oe("message",_),o&&(_=o(_));let{prefix:L,scalar:P,pointBytes:F}=M(x),K=ie(B.context,L,_),Y=R.multiply(K).toRawBytes(),H=ie(B.context,Y,F,_),G=q(K+H*P);w(G);let ue=Ct(Y,wr(G,t.BYTES));return oe("result",ue,a*2)}let I=ng;function k(_,x,B,L=I){let{context:P,zip215:F}=L,K=t.BYTES;_=oe("signature",_,2*K),x=oe("message",x),o&&(x=o(x));let Y=Xt(_.slice(K,2*K)),H,G,ue;try{H=v.fromHex(B,F),G=v.fromHex(_.slice(0,K),F),ue=R.multiplyUnsafe(Y)}catch{return!1}if(!F&&H.isSmallOrder())return!1;let re=ie(P,G.toRawBytes(),H.toRawBytes(),x);return G.add(H.multiplyUnsafe(re)).subtract(ue).clearCofactor().equals(v.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:le,sign:We,verify:k,ExtendedPoint:v,utils:{getExtendedPublicKey:M,randomPrivateKey:()=>i(t.BYTES),precompute(_=8,x=v.BASE){return x._setWindowSize(_),x.multiply(BigInt(3)),x}}}}var Ca=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ru=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),jE=BigInt(0),sg=BigInt(1),Ba=BigInt(2),ig=BigInt(5),Iu=BigInt(10),ag=BigInt(20),cg=BigInt(40),_u=BigInt(80);function lg(r){let e=Ca,n=r*r%e*r%e,o=J(n,Ba,e)*n%e,s=J(o,sg,e)*r%e,i=J(s,ig,e)*s%e,a=J(i,Iu,e)*i%e,c=J(a,ag,e)*a%e,u=J(c,cg,e)*c%e,f=J(u,_u,e)*u%e,l=J(f,_u,e)*u%e,p=J(l,Iu,e)*i%e;return{pow_p_5_8:J(p,Ba,e)*r%e,b2:n}}function ug(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function fg(r,e){let t=Ca,n=X(e*e*e,t),o=X(n*n*e,t),s=lg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*Ru,t),f=a===r,l=a===X(-r,t),p=a===X(-r*Ru,t);return f&&(i=c),(l||p)&&(i=u),Eu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Tt=Lo(Ca,void 0,!0),Ta={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Tt,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Qr,randomBytes:Zr,adjustScalarBytes:ug,uvRatio:fg},en=Oo(Ta);function Su(r,e,t){if(e.length>255)throw new Error("Context is too big");return So(ya("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var YE=Oo({...Ta,domain:Su}),WE=Oo({...Ta,domain:Su,prehash:Qr});var hg=(Tt.ORDER+BigInt(3))/BigInt(8),XE=Tt.pow(Ba,hg),ZE=Tt.sqrt(Tt.neg(Tt.ONE)),JE=(Tt.ORDER-BigInt(5))/BigInt(8),QE=BigInt(486662);var ex=xu(Tt,Tt.neg(BigInt(486664)));var tx=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),rx=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),nx=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),ox=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var sx=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var tn=32,Nt=64,Mo=32;function Bu(){let r=en.utils.randomPrivateKey(),e=en.getPublicKey(r);return{privateKey:ku(r,e),publicKey:e}}function Cu(r){if(r.length!==Mo)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=en.getPublicKey(e);return{privateKey:ku(e,t),publicKey:t}}function Tu(r,e){let t=r.subarray(0,Mo);return en.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Nu(r,e,t){return en.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function ku(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Mo;n++)t[n]=r[n],t[Mo+n]=e[n];return t}var Ie={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/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Na={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function ka(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ie.get();t*=8;async function c(l,p){let h=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:d};typeof p=="string"&&(p=D(p));let m;if(p.length===0){m=await a.subtle.importKey("jwk",Na,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",Na,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(g,m,l);return ge([h,g.iv,new Uint8Array(y)])}async function u(l,p){let h=l.subarray(0,s),d=l.subarray(s,s+n),g=l.subarray(s+n),m={name:e,iv:d};typeof p=="string"&&(p=D(p));let y;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",Na,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let w=await a.subtle.decrypt(m,y,g);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function rn(r,e){let n=await ka().encrypt(r,e);return Gr.encode(n)}var La=new Float32Array([-0]),Jt=new Uint8Array(La.buffer);function Du(r,e,t){La[0]=r,e[t]=Jt[0],e[t+1]=Jt[1],e[t+2]=Jt[2],e[t+3]=Jt[3]}function Pu(r,e){return Jt[0]=r[e],Jt[1]=r[e+1],Jt[2]=r[e+2],Jt[3]=r[e+3],La[0]}var Da=new Float64Array([-0]),De=new Uint8Array(Da.buffer);function Ou(r,e,t){Da[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function Mu(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],Da[0]}var pg=BigInt(Number.MAX_SAFE_INTEGER),mg=BigInt(Number.MIN_SAFE_INTEGER),Ke=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Er;if(e<pg&&e>mg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Uu&&(o=0n,++n>Uu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Er;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Er}},Er=new Ke(0,0);Er.toBigInt=function(){return 0n};Er.zzEncode=Er.zzDecode=function(){return this};Er.length=function(){return 1};var Uu=4294967296n;function Fu(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Vu(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Pa(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function at(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Uo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Oa=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(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,at(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw at(this,4);return Uo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return Uo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=Pu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Mu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw at(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw at(this,e);this.pos+=e}else do if(this.pos>=this.len)throw at(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ke(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw at(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw at(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw at(this,8);let e=Uo(this.buf,this.pos+=4),t=Uo(this.buf,this.pos+=4);return new Ke(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ma(r){return new Oa(r instanceof Uint8Array?r:r.subarray())}function _e(r,e){let t=Ma(r);return e.decode(t)}function Ua(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Le(i);o+i>e&&(n=Le(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var xr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Fa(){}var Ka=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},gg=Ua();function yg(r){return globalThis.Buffer!=null?Le(r):gg(r)}var qn=class{len;head;tail;states;constructor(){this.len=0,this.head=new xr(Fa,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new xr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $a((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push($n,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ke.fromBigInt(e);return this._push($n,t.length(),t)}uint64Number(e){let t=Ke.fromNumber(e);return this._push($n,t.length(),t)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ke.fromBigInt(e).zzEncode();return this._push($n,t.length(),t)}sint64Number(e){let t=Ke.fromNumber(e).zzEncode();return this._push($n,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Va,1,e?1:0)}fixed32(e){return this._push(Hn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ke.fromBigInt(e);return this._push(Hn,4,t.lo)._push(Hn,4,t.hi)}fixed64Number(e){let t=Ke.fromNumber(e);return this._push(Hn,4,t.lo)._push(Hn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Du,4,e)}double(e){return this._push(Ou,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Va,1,0):this.uint32(t)._push(bg,t,e)}string(e){let t=Fu(e);return t!==0?this.uint32(t)._push(Pa,t,e):this._push(Va,1,0)}fork(){return this.states=new Ka(this),this.head=this.tail=new xr(Fa,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new xr(Fa,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=yg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Va(r,e,t){e[t]=r&255}function wg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var $a=class extends xr{next;constructor(e,t){super(wg,e,t),this.next=void 0}};function $n(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Hn(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 bg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(qn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Eg,e,r),this},qn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xg,e,r),this});function Eg(r,e,t){e.set(r,t)}function xg(r,e,t){r.length<40?Pa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function Ha(){return new qn}function Se(r,e){let t=Ha();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var nn;(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"})(nn||(nn={}));function Fo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function qa(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Fo("enum",nn.VARINT,t,n)}function Be(r,e){return Fo("message",nn.LENGTH_DELIMITED,r,e)}var Q;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Q||(Q={}));var za;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(za||(za={}));(function(r){r.codec=()=>qa(za)})(Q||(Q={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(gt||(gt={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Q.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Q.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(yt||(yt={}));var on=class{_key;constructor(e){this._key=sn(e,tn)}verify(e,t){return Nu(this._key,t,e)}marshal(){return this._key}get bytes(){return gt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},Qt=class{_key;_publicKey;constructor(e,t){this._key=sn(e,Nt),this._publicKey=sn(t,tn)}sign(e){return Tu(this._key,e)}get public(){return new on(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Ze(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=qt.digest(this.public.bytes);return ee.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function vg(r){if(r.length>Nt){r=sn(r,Nt+tn);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Qt(n,o)}r=sn(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(tn);return new Qt(e,t)}function Ag(r){return r=sn(r,tn),new on(r)}async function Rg(){let{privateKey:r,publicKey:e}=Bu();return new Qt(r,e)}async function $u(r){let{privateKey:e,publicKey:t}=Cu(r);return new Qt(e,t)}function sn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function V(r,e="utf8"){let t=Ro[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 Ig={"P-256":256,"P-384":384,"P-521":521},_g=Object.keys(Ig),iv=_g.join(" / ");var rc={};be(rc,{MAX_RSA_KEY_SIZE:()=>hn,RsaPrivateKey:()=>Rr,RsaPublicKey:()=>fn,fromJwk:()=>Qg,generateKeyPair:()=>e0,unmarshalRsaPrivateKey:()=>ec,unmarshalRsaPublicKey:()=>Jg});function vr(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Zr(r)}var nr={};be(nr,{exportToPem:()=>Yg,importFromPem:()=>kf,jwkToPkcs1:()=>qg,jwkToPkix:()=>Gg,pkcs1ToJwk:()=>Hg,pkixToJwk:()=>zg});var Ko=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Io(e);let n=jt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),ga(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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,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()}},zn=(r,e,t)=>new Ko(r,e).update(t).digest();zn.create=(r,e)=>new Ko(r,e);function Bg(r,e,t,n){Io(r);let o=hu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(jr(s),jr(i),jr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=jt(e),u=jt(t),f=new Uint8Array(i),l=zn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Cg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function ja(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Bg(r,e,t,n),f,l=new Uint8Array(4),p=Xr(l),h=new Uint8Array(c.outputLen);for(let d=1,g=0;g<s;d++,g+=c.outputLen){let m=a.subarray(g,g+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),m.set(h.subarray(0,m.length)),await fu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let y=0;y<m.length;y++)m[y]^=h[y]})}return Cg(c,u,a,f,h)}var $=dt(Hu());function Ar(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function er(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function qo(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Wa(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Ar(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Ar(s,8)-n}function qu(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function zu(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function $e(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Lv=Math.log(2);function zo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Xa(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ot(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var jn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Xa(this.items)}},Gn=[new Uint8Array([1])],Gu="0123456789";var ln="",lt=new ArrayBuffer(0),Za=new Uint8Array(0),Yn="EndOfContent",Yu="OCTET STRING",Wu="BIT STRING";function Mt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?$.BufferSourceConverter.toUint8Array(s.valueHex):Za}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",lt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:$.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=ln,warnings:n=[],valueBeforeDecode:o=Za}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=$.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:$.Convert.ToHex(this.valueBeforeDecodeView)}}};Lt.NAME="baseBlock";var Pe=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pe.NAME="valueBlock";var Go=class extends Mt(Lt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?$.BufferSourceConverter.toUint8Array(e.valueHex):Za,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",lt}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=er(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let p=0;p<c;p++)l[p]=u[p];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Ar(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Go.NAME="identificationBlock";var jo=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ar(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=er(this.length,8);if(o.byteLength>127)return this.error="Too big length",lt;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};jo.NAME="lengthBlock";var S={},Ce=class extends Lt{constructor({name:e=ln,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Go(o),this.lenBlock=new jo(o),this.valueBlock=s?new s(o):new Pe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new jn;t||Xu(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?lt:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():$.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${$.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return zu(t,n)}};Ce.NAME="BaseBlock";function Xu(r){if(r instanceof S.Constructed)for(let e of r.valueBlock.value)Xu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Yo=class extends Ce{constructor({value:e=ln,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Yo.NAME="BaseStringBlock";var Wo=class extends Mt(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Wo.NAME="PrimitiveValueBlock";var Zu,Xo=class extends Ce{constructor(e={}){super(e,Wo),this.idBlock.isConstructed=!1}};Zu=Xo;S.Primitive=Zu;Xo.NAME="PRIMITIVE";function Ug(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Cs(r,e=0,t=r.length){let n=e,o=new Ce({},Pe),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ce;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=S.EndOfContent;break;case 1:c=S.Boolean;break;case 2:c=S.Integer;break;case 3:c=S.BitString;break;case 4:c=S.OctetString;break;case 5:c=S.Null;break;case 6:c=S.ObjectIdentifier;break;case 10:c=S.Enumerated;break;case 12:c=S.Utf8String;break;case 13:c=S.RelativeObjectIdentifier;break;case 14:c=S.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=S.Sequence;break;case 17:c=S.Set;break;case 18:c=S.NumericString;break;case 19:c=S.PrintableString;break;case 20:c=S.TeletexString;break;case 21:c=S.VideotexString;break;case 22:c=S.IA5String;break;case 23:c=S.UTCTime;break;case 24:c=S.GeneralizedTime;break;case 25:c=S.GraphicString;break;case 26:c=S.VisibleString;break;case 27:c=S.GeneralString;break;case 28:c=S.UniversalString;break;case 29:c=S.CharacterString;break;case 30:c=S.BmpString;break;case 31:c=S.DATE;break;case 32:c=S.TimeOfDay;break;case 33:c=S.DateTime;break;case 34:c=S.Duration;break;default:{let u=o.idBlock.isConstructed?new S.Constructed:new S.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?S.Constructed:S.Primitive}return o=Ug(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function un(r){if(!r.byteLength){let e=new Ce({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Cs($.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Fg(r,e){return r?1:e}var wt=class extends Pe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;Fg(this.isIndefiniteForm,n)>0;){let i=Cs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Yn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new jn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?lt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wt.NAME="ConstructedValueBlock";var Ju,tr=class extends Ce{constructor(e={}){super(e,wt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
3
|
-
`).map(o=>` ${o}`).join(`
|
|
4
|
-
|
|
5
|
-
${e.join(`
|
|
6
|
-
`)}`:`${t} :`}};Ju=tr;S.Constructed=Ju;tr.NAME="CONSTRUCTED";var Zo=class extends Pe{fromBER(e,t,n){return t}toBER(e){return lt}};Zo.override="EndOfContentValueBlock";var Qu,Jo=class extends Ce{constructor(e={}){super(e,Zo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Qu=Jo;S.EndOfContent=Qu;Jo.NAME=Yn;var ef,rr=class extends Ce{constructor(e={}){super(e,Pe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ef=rr;S.Null=ef;rr.NAME="NULL";var Qo=class extends Mt(Pe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=$.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=$.BufferSourceConverter.toUint8Array(e);return Ot(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Wa.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Qo.NAME="BooleanValueBlock";var tf,es=class extends Ce{constructor(e={}){super(e,Qo),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};tf=es;S.Boolean=tf;es.NAME="BOOLEAN";var ts=class extends Mt(wt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Yu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ts.NAME="OctetStringValueBlock";var rf,Dt=class r extends Ce{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ts),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Cs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?tr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${$.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return $.BufferSourceConverter.concat(e)}};rf=Dt;S.OctetString=rf;Dt.NAME=Yu;var rs=class extends Mt(wt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Wu)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Cs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return wt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};rs.NAME="BitStringValueBlock";var nf,cn=class extends Ce{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return tr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};nf=cn;S.BitString=nf;cn.NAME=Wu;var of;function Vg(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let p=f;p>=0;p--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=qo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=qo(t,s)),s}function ju(r){if(r>=Gn.length)for(let e=Gn.length;e<=r;e++){let t=new Uint8Array([0]),n=Gn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=qo(t,n)),Gn.push(n)}return Gn[r]}function Kg(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Wn=class extends Mt(Pe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Wa.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(qu(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Kg(ju(n),t),i="-";break;default:t=Vg(t,ju(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Gu.charAt(t[c]));return a===!1&&(i+=Gu.charAt(0)),i}};of=Wn;Wn.NAME="IntegerValueBlock";Object.defineProperty(of.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var sf,fe=class r extends Ce{constructor(e={}){super(e,Wn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return zo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){zo();let t=BigInt(e),n=new jn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array($.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${$.Convert.ToHex(a)}`)+t,f=$.BufferSourceConverter.toUint8Array($.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};sf=fe;S.Integer=sf;fe.NAME="INTEGER";var af,ns=class extends fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};af=ns;S.Enumerated=af;ns.NAME="ENUMERATED";var Xn=class extends Mt(Pe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){zo();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=$.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Xn.NAME="sidBlock";var os=class extends Pe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Xn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,lt;t.push(o)}return Xa(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Xn;if(o>Number.MAX_SAFE_INTEGER){zo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};os.NAME="ObjectIdentifierValueBlock";var cf,ct=class extends Ce{constructor(e={}){super(e,os),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};cf=ct;S.ObjectIdentifier=cf;ct.NAME="OBJECT IDENTIFIER";var Zn=class extends Mt(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=$.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=$.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Zn.NAME="relativeSidBlock";var ss=class extends Pe{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Zn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,lt;n.push(s)}return Xa(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Zn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ss.NAME="RelativeObjectIdentifierValueBlock";var lf,is=class extends Ce{constructor(e={}){super(e,ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};lf=is;S.RelativeObjectIdentifier=lf;is.NAME="RelativeObjectIdentifier";var uf,Ee=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};uf=Ee;S.Sequence=uf;Ee.NAME="SEQUENCE";var ff,as=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ff=as;S.Set=ff;as.NAME="SET";var cs=class extends Mt(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ln}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="StringValueBlock";var ls=class extends cs{};ls.NAME="SimpleStringValueBlock";var Fe=class extends Yo{constructor({...e}={}){super(e,ls)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,$.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Fe.NAME="SIMPLE STRING";var us=class extends Fe{fromBuffer(e){this.valueBlock.valueHexView=$.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=$.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=$.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array($.Convert.FromUtf8String(e)),this.valueBlock.value=e}};us.NAME="Utf8StringValueBlock";var hf,Pt=class extends us{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};hf=Pt;S.Utf8String=hf;Pt.NAME="UTF8String";var fs=class extends Fe{fromBuffer(e){this.valueBlock.value=$.Convert.ToUtf16String(e),this.valueBlock.valueHexView=$.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array($.Convert.FromUtf16String(e))}};fs.NAME="BmpStringValueBlock";var df,hs=class extends fs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};df=hs;S.BmpString=df;hs.NAME="BMPString";var ds=class extends Fe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=er(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};ds.NAME="UniversalStringValueBlock";var pf,ps=class extends ds{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};pf=ps;S.UniversalString=pf;ps.NAME="UniversalString";var mf,ms=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};mf=ms;S.NumericString=mf;ms.NAME="NumericString";var gf,gs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};gf=gs;S.PrintableString=gf;gs.NAME="PrintableString";var yf,ys=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};yf=ys;S.TeletexString=yf;ys.NAME="TeletexString";var wf,ws=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};wf=ws;S.VideotexString=wf;ws.NAME="VideotexString";var bf,bs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};bf=bs;S.IA5String=bf;bs.NAME="IA5String";var Ef,Es=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ef=Es;S.GraphicString=Ef;Es.NAME="GraphicString";var xf,Jn=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};xf=Jn;S.VisibleString=xf;Jn.NAME="VisibleString";var vf,xs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};vf=xs;S.GeneralString=vf;xs.NAME="GeneralString";var Af,vs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Af=vs;S.CharacterString=Af;vs.NAME="CharacterString";var Rf,Qn=class extends Jn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,$.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=$e(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=$e(this.month,2),t[2]=$e(this.day,2),t[3]=$e(this.hour,2),t[4]=$e(this.minute,2),t[5]=$e(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Rf=Qn;S.UTCTime=Rf;Qn.NAME="UTCTime";var If,As=class extends Qn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),l=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(h.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,h.length===4){if(d=parseInt(h.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push($e(this.year,4)),t.push($e(this.month,2)),t.push($e(this.day,2)),t.push($e(this.hour,2)),t.push($e(this.minute,2)),t.push($e(this.second,2)),this.millisecond!==0&&(t.push("."),t.push($e(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};If=As;S.GeneralizedTime=If;As.NAME="GeneralizedTime";var _f,Rs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};_f=Rs;S.DATE=_f;Rs.NAME="DATE";var Sf,Is=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Sf=Is;S.TimeOfDay=Sf;Is.NAME="TimeOfDay";var Bf,_s=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Bf=_s;S.DateTime=Bf;_s.NAME="DateTime";var Cf,Ss=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Cf=Ss;S.Duration=Cf;Ss.NAME="Duration";var Tf,Bs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Tf=Bs;S.TIME=Tf;Bs.NAME="TIME";function Hg(r){let{result:e}=un(r),t=e.valueBlock.value;return{n:V(bt(t[1].toBigInt()),"base64url"),e:V(bt(t[2].toBigInt()),"base64url"),d:V(bt(t[3].toBigInt()),"base64url"),p:V(bt(t[4].toBigInt()),"base64url"),q:V(bt(t[5].toBigInt()),"base64url"),dp:V(bt(t[6].toBigInt()),"base64url"),dq:V(bt(t[7].toBigInt()),"base64url"),qi:V(bt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function qg(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 E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new fe({value:0}),fe.fromBigInt(Et(D(r.n,"base64url"))),fe.fromBigInt(Et(D(r.e,"base64url"))),fe.fromBigInt(Et(D(r.d,"base64url"))),fe.fromBigInt(Et(D(r.p,"base64url"))),fe.fromBigInt(Et(D(r.q,"base64url"))),fe.fromBigInt(Et(D(r.dp,"base64url"))),fe.fromBigInt(Et(D(r.dq,"base64url"))),fe.fromBigInt(Et(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function zg(r){let{result:e}=un(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:V(bt(t[0].toBigInt()),"base64url"),e:V(bt(t[1].toBigInt()),"base64url")}}function Gg(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new rr]}),new cn({valueHex:new Ee({value:[fe.fromBigInt(Et(D(r.n,"base64url"))),fe.fromBigInt(Et(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function Et(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var jg=16,Ja=32,Qa=1e4;async function Yg(r,e){let t=Ie.get(),o=new Ee({value:[new fe({value:0}),new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new rr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=vr(jg),a=await ja(Qr,e,i,{c:Qa,dkLen:Ja}),c=vr(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new Ee({value:[new Dt({valueHex:i}),new fe({value:Qa}),new fe({value:Ja}),new Ee({value:[new ct({value:"1.2.840.113549.2.11"}),new rr]})]}),p=new Ee({value:[new ct({value:"1.2.840.113549.1.5.13"}),new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.5.12"}),l]}),new Ee({value:[new ct({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new Ee({value:[p,new Dt({valueHex:f})]}).toBER(),g=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...V(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
7
|
-
`)}async function kf(r,e){let t=Ie.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=un(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Wg(s),l=await ja(Qr,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=eo(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=un(h);n=Nf(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=un(o);n=Nf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return ec(n)}function Wg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new E("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=eo(s.valueBlock.value[0].getValue()),a=Qa,c=Ja;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new E("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new E("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=eo(u.valueBlock.value[1].getValue());return{cipherText:eo(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Nf(r){return eo(r.valueBlock.value[2].getValue())}function eo(r){return new Uint8Array(r,0,r.byteLength)}async function Lf(r){let e=await Ie.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 Of(e);return{privateKey:t[0],publicKey:t[1]}}async function tc(r){let t=[await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Xg(r)],n=await Of({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Df(r,e){let t=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ie.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Pf(r,e,t){let n=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ie.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Of(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ie.get().subtle.exportKey("jwk",r.privateKey),Ie.get().subtle.exportKey("jwk",r.publicKey)])}async function Xg(r){return Ie.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 Ts(r){if(r.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var hn=8192,fn=class{_key;constructor(e){this._key=e}verify(e,t){return Pf(this._key,t,e)}marshal(){return nr.jwkToPkix(this._key)}get bytes(){return gt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}},Rr=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return vr(16)}sign(e){return Df(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fn(this._publicKey)}marshal(){return nr.jwkToPkcs1(this._key)}get bytes(){return yt.encode({Type:Q.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return nr.exportToPem(this,e);if(t==="libp2p-key")return rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function ec(r){let e=nr.pkcs1ToJwk(r);if(Ts(e)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await tc(e);return new Rr(t.privateKey,t.publicKey)}function Jg(r){let e=nr.pkixToJwk(r);if(Ts(e)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fn(e)}async function Qg(r){if(Ts(r)>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await tc(r);return new Rr(e.privateKey,e.publicKey)}async function e0(r){if(r>hn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Lf(r);return new Rr(e.privateKey,e.publicKey)}var ac={};be(ac,{Secp256k1PrivateKey:()=>pn,Secp256k1PublicKey:()=>dn,generateKeyPair:()=>m0,unmarshalSecp256k1PrivateKey:()=>d0,unmarshalSecp256k1PublicKey:()=>p0});var t0=(r,e,t)=>r&e^~r&t,r0=(r,e,t)=>r&e^r&t^e&t,n0=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]),or=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),sr=new Uint32Array(64),nc=class extends Jr{constructor(){super(64,32,8,!1),this.A=or[0]|0,this.B=or[1]|0,this.C=or[2]|0,this.D=or[3]|0,this.E=or[4]|0,this.F=or[5]|0,this.G=or[6]|0,this.H=or[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)sr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=sr[l-15],h=sr[l-2],d=ot(p,7)^ot(p,18)^p>>>3,g=ot(h,17)^ot(h,19)^h>>>10;sr[l]=g+sr[l-7]+d+sr[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let p=ot(a,6)^ot(a,11)^ot(a,25),h=f+p+t0(a,c,u)+n0[l]+sr[l]|0,g=(ot(n,2)^ot(n,13)^ot(n,22))+r0(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){sr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Mf=Bo(()=>new nc);function o0(r){let e=Kn(r);mt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:s0,hexToBytes:i0}=No,Ir={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Ir;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:s0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Ir,t=typeof r=="string"?i0(r):r;if(!st(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Ir._parseInt(t.subarray(2)),{d:i,l:a}=Ir._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Ut=BigInt(0),Qe=BigInt(1),s1=BigInt(2),Uf=BigInt(3),i1=BigInt(4);function a0(r){let e=o0(r),{Fp:t}=e,n=e.toBytes||((d,g,m)=>{let y=g.toAffine();return Ct(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),o=e.fromBytes||(d=>{let g=d.subarray(1),m=t.fromBytes(g.subarray(0,t.BYTES)),y=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:m,y}});function s(d){let{a:g,b:m}=e,y=t.sqr(d),w=t.mul(y,d);return t.add(t.add(w,t.mul(d,g)),m)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Ut<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:g,nByteLength:m,wrapPrivateKey:y,n:w}=e;if(g&&typeof d!="bigint"){if(st(d)&&(d=St(d)),typeof d!="string"||!g.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(oe("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return y&&(b=X(b,w)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(g,m,y){if(this.px=g,this.py=m,this.pz=y,g==null||!t.isValid(g))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required")}static fromAffine(g){let{x:m,y}=g||{};if(!g||!t.isValid(m)||!t.isValid(y))throw new Error("invalid affine point");if(g instanceof l)throw new Error("projective point not allowed");let w=b=>t.eql(b,t.ZERO);return w(m)&&w(y)?l.ZERO:new l(m,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let m=t.invertBatch(g.map(y=>y.pz));return g.map((y,w)=>y.toAffine(m[w])).map(l.fromAffine)}static fromHex(g){let m=l.fromAffine(o(oe("pointHex",g)));return m.assertValidity(),m}static fromPrivateKey(g){return l.BASE.multiply(c(g))}_setWindowSize(g){this._WINDOW_SIZE=g,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:g,y:m}=this.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not FE");let y=t.sqr(m),w=s(g);if(!t.eql(y,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){f(g);let{px:m,py:y,pz:w}=this,{px:b,py:A,pz:v}=g,R=t.eql(t.mul(m,v),t.mul(b,w)),T=t.eql(t.mul(y,v),t.mul(A,w));return R&&T}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:m}=e,y=t.mul(m,Uf),{px:w,py:b,pz:A}=this,v=t.ZERO,R=t.ZERO,T=t.ZERO,N=t.mul(w,w),q=t.mul(b,b),z=t.mul(A,A),M=t.mul(w,b);return M=t.add(M,M),T=t.mul(w,A),T=t.add(T,T),v=t.mul(g,T),R=t.mul(y,z),R=t.add(v,R),v=t.sub(q,R),R=t.add(q,R),R=t.mul(v,R),v=t.mul(M,v),T=t.mul(y,T),z=t.mul(g,z),M=t.sub(N,z),M=t.mul(g,M),M=t.add(M,T),T=t.add(N,N),N=t.add(T,N),N=t.add(N,z),N=t.mul(N,M),R=t.add(R,N),z=t.mul(b,A),z=t.add(z,z),N=t.mul(z,M),v=t.sub(v,N),T=t.mul(z,q),T=t.add(T,T),T=t.add(T,T),new l(v,R,T)}add(g){f(g);let{px:m,py:y,pz:w}=this,{px:b,py:A,pz:v}=g,R=t.ZERO,T=t.ZERO,N=t.ZERO,q=e.a,z=t.mul(e.b,Uf),M=t.mul(m,b),le=t.mul(y,A),ie=t.mul(w,v),We=t.add(m,y),I=t.add(b,A);We=t.mul(We,I),I=t.add(M,le),We=t.sub(We,I),I=t.add(m,w);let k=t.add(b,v);return I=t.mul(I,k),k=t.add(M,ie),I=t.sub(I,k),k=t.add(y,w),R=t.add(A,v),k=t.mul(k,R),R=t.add(le,ie),k=t.sub(k,R),N=t.mul(q,I),R=t.mul(z,ie),N=t.add(R,N),R=t.sub(le,N),N=t.add(le,N),T=t.mul(R,N),le=t.add(M,M),le=t.add(le,M),ie=t.mul(q,ie),I=t.mul(z,I),le=t.add(le,ie),ie=t.sub(M,ie),ie=t.mul(q,ie),I=t.add(I,ie),M=t.mul(le,I),T=t.add(T,M),M=t.mul(k,I),R=t.mul(We,R),R=t.sub(R,M),M=t.mul(We,le),N=t.mul(k,N),N=t.add(N,M),new l(R,T,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(l.ZERO)}wNAF(g){return h.wNAFCached(this,u,g,m=>{let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(l.fromAffine)})}multiplyUnsafe(g){let m=l.ZERO;if(g===Ut)return m;if(a(g),g===Qe)return this;let{endo:y}=e;if(!y)return h.unsafeLadder(this,g);let{k1neg:w,k1:b,k2neg:A,k2:v}=y.splitScalar(g),R=m,T=m,N=this;for(;b>Ut||v>Ut;)b&Qe&&(R=R.add(N)),v&Qe&&(T=T.add(N)),N=N.double(),b>>=Qe,v>>=Qe;return w&&(R=R.negate()),A&&(T=T.negate()),T=new l(t.mul(T.px,y.beta),T.py,T.pz),R.add(T)}multiply(g){a(g);let m=g,y,w,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:R,k2:T}=b.splitScalar(m),{p:N,f:q}=this.wNAF(v),{p:z,f:M}=this.wNAF(T);N=h.constTimeNegate(A,N),z=h.constTimeNegate(R,z),z=new l(t.mul(z.px,b.beta),z.py,z.pz),y=N.add(z),w=q.add(M)}else{let{p:A,f:v}=this.wNAF(m);y=A,w=v}return l.normalizeZ([y,w])[0]}multiplyAndAddUnsafe(g,m,y){let w=l.BASE,b=(v,R)=>R===Ut||R===Qe||!v.equals(w)?v.multiplyUnsafe(R):v.multiply(R),A=b(this,m).add(b(g,y));return A.is0()?void 0:A}toAffine(g){let{px:m,py:y,pz:w}=this,b=this.is0();g==null&&(g=b?t.ONE:t.inv(w));let A=t.mul(m,g),v=t.mul(y,g),R=t.mul(w,g);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:g,isTorsionFree:m}=e;if(g===Qe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:m}=e;return g===Qe?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return this.assertValidity(),n(l,this,g)}toHex(g=!0){return St(this.toRawBytes(g))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=Do(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function c0(r){let e=Kn(r);return mt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ff(r){let e=c0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Ut<I&&I<t.ORDER}function a(I){return X(I,n)}function c(I){return ko(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=a0({...e,toBytes(I,k,U){let _=k.toAffine(),x=t.toBytes(_.x),B=Ct;return U?B(Uint8Array.from([k.hasEvenY()?2:3]),x):B(Uint8Array.from([4]),x,t.toBytes(_.y))},fromBytes(I){let k=I.length,U=I[0],_=I.subarray(1);if(k===o&&(U===2||U===3)){let x=Bt(_);if(!i(x))throw new Error("Point is not on curve");let B=l(x),L=t.sqrt(B),P=(L&Qe)===Qe;return(U&1)===1!==P&&(L=t.neg(L)),{x,y:L}}else if(k===s&&U===4){let x=t.fromBytes(_.subarray(0,t.BYTES)),B=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x,y:B}}else throw new Error(`Point of length ${k} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>St(Zt(I,e.nByteLength));function d(I){let k=n>>Qe;return I>k}function g(I){return d(I)?a(-I):I}let m=(I,k,U)=>Bt(I.slice(k,U));class y{constructor(k,U,_){this.r=k,this.s=U,this.recovery=_,this.assertValidity()}static fromCompact(k){let U=e.nByteLength;return k=oe("compactSignature",k,U*2),new y(m(k,0,U),m(k,U,2*U))}static fromDER(k){let{r:U,s:_}=Ir.toSig(oe("DER",k));return new y(U,_)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:U,s:_,recovery:x}=this,B=T(oe("msgHash",k));if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");let L=x===2||x===3?U+e.n:U;if(L>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=x&1?"03":"02",F=u.fromHex(P+h(L)),K=c(L),Y=a(-B*K),H=a(_*K),G=u.BASE.multiplyAndAddUnsafe(F,Y,H);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return yr(this.toDERHex())}toDERHex(){return Ir.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=_a(e.n);return Au(e.randomBytes(I),e.n)},precompute(I=8,k=u.BASE){return k._setWindowSize(I),k.multiply(BigInt(3)),k}};function b(I,k=!0){return u.fromPrivateKey(I).toRawBytes(k)}function A(I){let k=st(I),U=typeof I=="string",_=(k||U)&&I.length;return k?_===o||_===s:U?_===2*o||_===2*s:I instanceof u}function v(I,k,U=!0){if(A(I))throw new Error("first arg must be private key");if(!A(k))throw new Error("second arg must be public key");return u.fromHex(k).multiply(f(I)).toRawBytes(U)}let R=e.bits2int||function(I){let k=Bt(I),U=I.length*8-e.nBitLength;return U>0?k>>BigInt(U):k},T=e.bits2int_modN||function(I){return a(R(I))},N=Vn(e.nBitLength);function q(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Ut<=I&&I<N))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Zt(I,e.nByteLength)}function z(I,k,U=M){if(["recovered","canonical"].some(re=>re in U))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:x}=e,{lowS:B,prehash:L,extraEntropy:P}=U;B==null&&(B=!0),I=oe("msgHash",I),L&&(I=oe("prehashed msgHash",_(I)));let F=T(I),K=f(k),Y=[q(K),q(F)];if(P!=null){let re=P===!0?x(t.BYTES):P;Y.push(oe("extraEntropy",re))}let H=Ct(...Y),G=F;function ue(re){let ve=R(re);if(!p(ve))return;let Ae=c(ve),me=u.BASE.multiply(ve).toAffine(),ke=a(me.x);if(ke===Ut)return;let At=a(Ae*a(G+ke*K));if(At===Ut)return;let dr=(me.x===ke?0:2)|Number(me.y&Qe),On=At;return B&&d(At)&&(On=g(At),dr^=1),new y(ke,On,dr)}return{seed:H,k2sig:ue}}let M={lowS:e.lowS,prehash:!1},le={lowS:e.lowS,prehash:!1};function ie(I,k,U=M){let{seed:_,k2sig:x}=z(I,k,U),B=e;return va(B.hash.outputLen,B.nByteLength,B.hmac)(_,x)}u.BASE._setWindowSize(8);function We(I,k,U,_=le){let x=I;if(k=oe("msgHash",k),U=oe("publicKey",U),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:B,prehash:L}=_,P,F;try{if(typeof x=="string"||st(x))try{P=y.fromDER(x)}catch(me){if(!(me instanceof Ir.Err))throw me;P=y.fromCompact(x)}else if(typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint"){let{r:me,s:ke}=x;P=new y(me,ke)}else throw new Error("PARSE");F=u.fromHex(U)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(B&&P.hasHighS())return!1;L&&(k=e.hash(k));let{r:K,s:Y}=P,H=T(k),G=c(Y),ue=a(H*G),re=a(K*G),ve=u.BASE.multiplyAndAddUnsafe(F,ue,re)?.toAffine();return ve?a(ve.x)===K:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ie,verify:We,ProjectivePoint:u,Signature:y,utils:w}}function l0(r){return{hash:r,hmac:(e,...t)=>zn(r,e,So(...t)),randomBytes:Zr}}function Vf(r,e){let t=n=>Ff({...r,...l0(n)});return Object.freeze({...t(e),create:t})}var Hf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Kf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),u0=BigInt(1),oc=BigInt(2),$f=(r,e)=>(r+e/oc)/e;function f0(r){let e=Hf,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=J(f,t,e)*f%e,p=J(l,t,e)*f%e,h=J(p,oc,e)*u%e,d=J(h,o,e)*h%e,g=J(d,s,e)*d%e,m=J(g,a,e)*g%e,y=J(m,c,e)*m%e,w=J(y,a,e)*g%e,b=J(w,t,e)*f%e,A=J(b,i,e)*d%e,v=J(A,n,e)*u%e,R=J(v,oc,e);if(!sc.eql(sc.sqr(R),r))throw new Error("Cannot find square root");return R}var sc=Lo(Hf,void 0,void 0,{sqrt:f0}),ut=Vf({a:BigInt(0),b:BigInt(7),Fp:sc,n:Kf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Kf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-u0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=$f(s*r,e),c=$f(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,p=f>i;if(l&&(u=e-u),p&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},Mf),m1=BigInt(0);var g1=ut.ProjectivePoint;function qf(){return ut.utils.randomPrivateKey()}function zf(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(Ze(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function Gf(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(Ze(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function jf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Yf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ic(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Wf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var dn=class{_key;constructor(e){ic(e),this._key=e}verify(e,t){return Gf(this._key,t,e)}marshal(){return jf(this._key)}get bytes(){return gt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Ze(e)?{bytes:t}=await e:t=e.bytes,t}},pn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Wf(e),Yf(this._key),ic(this._publicKey)}sign(e){return zf(this._key,e)}get public(){return new dn(this._publicKey)}marshal(){return this._key}get bytes(){return yt.encode({Type:Q.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Ze(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return rn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function d0(r){return new pn(r)}function p0(r){return new dn(r)}async function m0(){let r=qf();return new pn(r)}var ir={rsa:rc,ed25519:Ga,secp256k1:ac};function cc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function lc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw cc(r)}async function Xf(r,e){return lc(r).generateKeyPair(e??2048)}function to(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return ir.rsa.unmarshalRsaPublicKey(t);case Q.Ed25519:return ir.ed25519.unmarshalEd25519PublicKey(t);case Q.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw cc(e.Type??"unknown")}}function Zf(r,e){return e=(e??"rsa").toLowerCase(),lc(e),r.bytes}async function uc(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Q.RSA:return ir.rsa.unmarshalRsaPrivateKey(t);case Q.Ed25519:return ir.ed25519.unmarshalEd25519PrivateKey(t);case Q.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw cc(e.Type??"RSA")}}function Jf(r,e){return e=(e??"rsa").toLowerCase(),lc(e),r.bytes}var Ye=dt(hc(),1);Ye.default.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);Ye.default.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);Ye.default.formatters.m=r=>r==null?"undefined":Gr.baseEncode(r);Ye.default.formatters.p=r=>r==null?"undefined":r.toString();Ye.default.formatters.c=r=>r==null?"undefined":r.toString();Ye.default.formatters.k=r=>r==null?"undefined":r.toString();Ye.default.formatters.a=r=>r==null?"undefined":r.toString();function B0(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 Ls(){return{forComponent(r){return C0(r)}}}function C0(r){let e=B0(`${r}:trace`);return Ye.default.enabled(`${r}:trace`)&&Ye.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,Ye.default)(`${r}:trace`)),Object.assign((0,Ye.default)(r),{error:(0,Ye.default)(`${r}:error`),trace:e})}var T0=Symbol.for("nodejs.util.inspect.custom"),rh=Object.values(Gt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Gt.identity.decoder),nh=114,dc=36,pc=37,ro=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qi]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return nt.createV1(nh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return he(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[T0](){return`PeerId(${this.toString()})`}},Sr=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Br=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Cr=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function oh(r){if(r.type==="RSA")return new Sr(r);if(r.type==="Ed25519")return new Br(r);if(r.type==="secp256k1")return new Cr(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function he(r,e){if(e=e??rh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ee.decode(`z${r}`));return r.startsWith("12D")?new Br({multihash:t}):r.startsWith("16U")?new Cr({multihash:t}):new Sr({multihash:t})}return wn(rh.decode(r))}function wn(r){try{let e=mr(r);if(e.code===qt.code){if(e.digest.length===dc)return new Br({multihash:e});if(e.digest.length===pc)return new Cr({multihash:e})}if(e.code===Re.code)return new Sr({multihash:e})}catch{return N0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function N0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==nh)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Re.code)return new Sr({multihash:r.multihash});if(e.code===qt.code){if(e.digest.length===dc)return new Br({multihash:r.multihash});if(e.digest.length===pc)return new Cr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ds(r,e){return r.length===dc?new Br({multihash:pt(qt.code,r),privateKey:e}):r.length===pc?new Cr({multihash:pt(qt.code,r),privateKey:e}):new Sr({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function Tr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var He=class{map;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){return this.map.delete(e.toString())}entries(){return Tr(this.map.entries(),e=>[he(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,he(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 Tr(this.map.keys(),e=>he(e))}values(){return this.map.values()}get size(){return this.map.size}};var et=class r{set;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 Tr(this.set.entries(),e=>{let t=he(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=he(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Tr(this.set.values(),e=>he(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var mc;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.id=t.bytes();break;case 2:o.pubKey=t.bytes();break;case 3:o.privKey=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(mc||(mc={}));var sh=async()=>{let r=await Xf("Ed25519"),e=await L0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function L0(r){return Ds(Zf(r.public),Jf(r))}var D0=Math.pow(2,7),P0=Math.pow(2,14),O0=Math.pow(2,21),gc=Math.pow(2,28),yc=Math.pow(2,35),wc=Math.pow(2,42),bc=Math.pow(2,49),j=128,Oe=127;function Me(r){if(r<D0)return 1;if(r<P0)return 2;if(r<O0)return 3;if(r<gc)return 4;if(r<yc)return 5;if(r<wc)return 6;if(r<bc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function M0(r,e,t=0){switch(Me(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function U0(r,e,t=0){switch(Me(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function F0(r,e){let t=r[e],n=0;if(n+=t&Oe,t<j||(t=r[e+1],n+=(t&Oe)<<7,t<j)||(t=r[e+2],n+=(t&Oe)<<14,t<j)||(t=r[e+3],n+=(t&Oe)<<21,t<j)||(t=r[e+4],n+=(t&Oe)*gc,t<j)||(t=r[e+5],n+=(t&Oe)*yc,t<j)||(t=r[e+6],n+=(t&Oe)*wc,t<j)||(t=r[e+7],n+=(t&Oe)*bc,t<j))return n;throw new RangeError("Could not decode varint")}function V0(r,e){let t=r.get(e),n=0;if(n+=t&Oe,t<j||(t=r.get(e+1),n+=(t&Oe)<<7,t<j)||(t=r.get(e+2),n+=(t&Oe)<<14,t<j)||(t=r.get(e+3),n+=(t&Oe)<<21,t<j)||(t=r.get(e+4),n+=(t&Oe)*gc,t<j)||(t=r.get(e+5),n+=(t&Oe)*yc,t<j)||(t=r.get(e+6),n+=(t&Oe)*wc,t<j)||(t=r.get(e+7),n+=(t&Oe)*bc,t<j))return n;throw new RangeError("Could not decode varint")}function qe(r,e,t=0){return e==null&&(e=Le(Me(r))),e instanceof Uint8Array?M0(r,e,t):U0(r,e,t)}function ft(r,e=0){return r instanceof Uint8Array?F0(r,e):V0(r,e)}var ah=Symbol.for("@achingbrain/uint8arraylist");function ih(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ps(r){return!!r?.[ah]}var xe=class r{bufs;length;[ah]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ps(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(Ps(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=ih(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ih(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(Ps(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:o}=this._subList(e,t);return ge(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ge(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ps(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let p=u;p>=0;p--){let h=this.get(l+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return l}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=Le(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 o=It(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=Le(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 o=It(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=It(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=It(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var ch={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var no;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={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 i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(no||(no={}));var bn=class r{static createFromProtobuf=async e=>{let t=no.decode(e),n=await Ds(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=lh(n,o,s),c=await(await uc(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new E("envelope signature is not valid for the given domain",ch.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=no.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return te(this.marshal(),e.marshal())}async validate(e){let t=lh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return to(this.peerId.publicKey).verify(t.subarray(),this.signature)}},lh=(r,e,t)=>{let n=D(r),o=qe(n.byteLength),s=qe(e.length),i=qe(t.length);return new xe(o,n,s,e,i,t)};function uh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Os=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var fh=45,K0=15,En=new Os;function Ec(r){if(!(r.length>K0))return En.new(r).parseWith(()=>En.readIPv4Addr())}function xc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>fh))return En.new(r).parseWith(()=>En.readIPv6Addr())}function Ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>fh))return En.new(r).parseWith(()=>En.readIPAddr())}var d2=parseInt("0xFFFF",16),p2=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Us(r){return!!Ec(r)}function Fs(r){return!!xc(r)}function xn(r){return!!Ms(r)}var ph=Us,G0=Fs,vc=function(r){let e=0;if(r=r.toString().trim(),ph(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(G0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ph(t[n]),i;s&&(i=vc(t[n]),t[n]=V(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,V(i.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 o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},mh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var vn={},Ac={},Y0=[[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"]];Y0.forEach(r=>{let e=W0(...r);Ac[e.code]=e,vn[e.name]=e});function W0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Ac[r]!=null)return Ac[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(vn[r]!=null)return vn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Z2=W("ip4"),J2=W("ip6"),Q2=W("ipcidr");function Ic(r,e){switch(W(r).code){case 4:case 41:return Z0(e);case 42:return wh(e);case 6:case 273:case 33:case 132:return Eh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return wh(e);case 421:return ty(e);case 444:return bh(e);case 445:return bh(e);case 466:return ey(e);default:return V(e,"base16")}}function _c(r,e){switch(W(r).code){case 4:return gh(e);case 41:return gh(e);case 42:return yh(e);case 6:case 273:case 33:case 132:return Sc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return yh(e);case 421:return J0(e);case 444:return ry(e);case 445:return ny(e);case 466:return Q0(e);default:return D(e,"base16")}}var Rc=Object.values(Gt).map(r=>r.decoder),X0=function(){let r=Rc[0].or(Rc[1]);return Rc.slice(2).forEach(e=>r=r.or(e)),r}();function gh(r){if(!xn(r))throw new Error("invalid ip address");return vc(r)}function Z0(r){let e=mh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!xn(e))throw new Error("invalid ip address");return e}function Sc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Eh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function yh(r){let e=D(r),t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function wh(r){let e=ft(r);if(r=r.slice(Me(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function J0(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ee.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function Q0(r){let e=X0.decode(r),t=Uint8Array.from(qe(e.length));return ge([t,e],t.length+e.length)}function ey(r){let e=ft(r),t=r.slice(Me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function ty(r){let e=ft(r),t=r.slice(Me(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function ry(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=ze.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 o=Sc(n);return ge([t,o],t.length+o.length)}function ny(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=ze.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 o=Sc(n);return ge([t,o],t.length+o.length)}function bh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=Eh(t);return`${n}:${o}`}function xh(r){r=Bc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Ah("invalid address: "+r);if(a.path===!0){n=Bc(o.slice(s).join("/")),e.push([a.code,_c(a.code,n)]),t.push([a.code,n]);break}let c=_c(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Ic(a.code,c)])}return{string:vh(t),bytes:Tc(e),tuples:e,stringTuples:t,path:n}}function Cc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=ft(r,o),i=Me(s),a=W(s),c=oy(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Ah("Invalid address Uint8Array: "+V(r,"base16"));e.push([s,u]);let f=Ic(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:vh(t),tuples:e,stringTuples:t,path:n}}function vh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Bc(e.join("/"))}function Tc(r){return ge(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(qe(t.code));return e.length>1&&e[1]!=null&&(n=ge([n,e[1]])),n}))}function oy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=ft(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Me(t)}}function Bc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Ah(r){return new Error("Error parsing address: "+r)}var sy=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),iy=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Vs=class r{bytes;#e;#t;#s;#a;[Nc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Cc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=xh(e)}else if(ar(e))t=Cc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),iy.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=W(h).name,n=`${d??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==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:o}}protos(){return this.#t.map(([e])=>Object.assign({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Tc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===vn.p2p.code&&e.push([n,o]),n===vn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ee.decode(`z${n}`),"base58btc"):V(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Ks.get(t.name);if(n==null)throw new E(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new r(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)}[sy](){return`Multiaddr(${this.#e})`}};var Ks=new Map;function ar(r){return!!r?.[Nc]}function se(r){return new Vs(r)}var Rh="libp2p-peer-record",Ih=Uint8Array.from([3,1]);var oo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;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})),o),n.encode=s=>Se(s,n.codec()),n.decode=s=>_e(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Be((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){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=>Se(n,r.codec()),r.decode=n=>_e(n,r.codec())})(oo||(oo={}));var kr=class r{static createFromProtobuf=e=>{let t=oo.decode(e),n=wn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Rh;static CODEC=Ih;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=oo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!uh(this.multiaddrs,e.multiaddrs))}};function ay(r){return r[Symbol.asyncIterator]!=null}function cy(r){if(ay(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 so=cy;var Lc=dt(Sh(),1);var ao=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Dc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Bh=r=>globalThis.DOMException===void 0?new Dc(r):new DOMException(r),Ch=r=>{let e=r.reason===void 0?Bh("This operation was aborted."):r.reason;return e instanceof Error?e:Bh(e)};function co(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(Ch(p)),p.addEventListener("abort",()=>{f(Ch(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new ao;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Pc(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var lo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Pc(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var An=class extends Lc.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:lo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${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 \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}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})`);this.#u=e,this.#h()}async#R(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=co(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof ao&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var cr={},Rn=r=>{r.addEventListener("message",e=>{Rn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Rn.dispatchEvent("message",r,e)})};Rn.addEventListener=(r,e)=>{cr[r]==null&&(cr[r]=[]),cr[r].push(e)};Rn.removeEventListener=(r,e)=>{cr[r]!=null&&(cr[r]=cr[r].filter(t=>t===e))};Rn.dispatchEvent=function(r,e,t){cr[r]!=null&&cr[r].forEach(n=>n(e,t))};var Oc=Rn;var Mc="lock:worker:request-read",Uc="lock:worker:release-read",Fc="lock:master:grant-read",Vc="lock:worker:request-write",Kc="lock:worker:release-write",$c="lock:master:grant-write";var Th=(r=21)=>Math.random().toString().substring(2);var Nh=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},kh=(r,e,t,n)=>async()=>{let o=Th();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},fy={singleProcess:!1},Lh=r=>{if(r=Object.assign({},fy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Oc.addEventListener("message",Nh(t,"requestReadLock",Mc,Uc,Fc)),Oc.addEventListener("message",Nh(t,"requestWriteLock",Vc,Kc,$c)),t}return{isWorker:!0,readLock:t=>kh(t,Mc,Fc,Uc),writeLock:t=>kh(t,Vc,$c,Kc)}};var Lr={},lr;async function Hc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>co((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var hy=(r,e)=>{if(lr.isWorker===!0)return{readLock:lr.readLock(r,e),writeLock:lr.writeLock(r,e)};let t=new An({concurrency:1}),n;return{async readLock(){if(n!=null)return Hc(n,e);n=new An({concurrency:e.concurrency,autoStart:!1});let o=n,s=Hc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Hc(t,e)}}},dy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function qc(r){let e=Object.assign({},dy,r);return lr==null&&(lr=Lh(e),lr.isWorker!==!0&&(lr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),lr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=hy(e.name,e)),Lr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var In;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Be((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Se(i,o.codec()),o.decode=i=>_e(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Be((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=qs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Se(i,o.codec()),o.decode=i=>_e(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Be((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Hs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Hs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Se(o,r.codec()),r.decode=o=>_e(o,r.codec())})(In||(In={}));var Hs;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(Hs||(Hs={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Be((t,n,o={})=>{o.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)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Se(t,r.codec()),r.decode=t=>_e(t,r.codec())})(qs||(qs={}));function _n(r,e){let t=In.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=oh({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",Dh=new TextEncoder().encode(Ft),zs=Dh[0],Dr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==zs)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Dh),this._buf[0]!==zs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(zs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===zs;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return py(this.baseNamespace())}name(){return my(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(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 r.withNamespaces([...this.namespaces(),...gy(e.map(t=>t.namespaces()))])}};function py(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function my(r){let e=r.split(":");return e[e.length-1]}function gy(r){return[].concat(...r)}var zc="/peers/";function Sn(r){if(!Eo(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${zc}${e}`)}async function Ph(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!ar(o.multiaddr))throw new E("Multiaddr was invalid",Te.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function js(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",Te.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new E("peer id did not match existing peer id",Te.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Gs(l,{validate:Oh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gs(l,{validate:Mh,map:Uh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,h]of l)h==null?a.delete(p):a.set(p,h);a=Gs([...a.entries()],{validate:Oh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[h,d]of l)d==null?p.delete(h):p.set(h,d);c=Gs([...p.entries()],{validate:Mh,map:Uh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Ph(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,p)=>l.localeCompare(p)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function Gs(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Oh(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Te.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Te.ERR_INVALID_PARAMETERS)}function Mh(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Te.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Te.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Te.ERR_INVALID_PARAMETERS)}}function Uh(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}}function Ys(r,e,t){let n=r.toString().split("/")[2],o=ze.decode(n),s=wn(o),i=t.get(s);if(i!=null)return i;let a=_n(s,e);return t.set(s,a),a}function yy(r,e){return r==null?{}:{prefix:zc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ys(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ys(n.key,n.value,e),Ys(o.key,o.value,e)))}}var Ws=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=qc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(Sn(e))}async load(e){let t=await this.datastore.get(Sn(e));return _n(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await js(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new He;for await(let{key:n,value:o}of this.datastore.query(yy(e??{},t))){let s=Ys(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Sn(e)),n=_n(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=In.encode(t);return n!=null&&te(s,n)?{peer:_n(e,s),previous:o,updated:!1}:(await this.datastore.put(Sn(e),s),{peer:_n(e,s),previous:o,updated:!0})}};var Xs=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Ws(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await so(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await bn.openAndCertify(e,kr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=kr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await bn.createFromProtobuf(s.peerRecordEnvelope),a=kr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!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 wy(r){return r[Symbol.asyncIterator]!=null}function by(r){if(wy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gc=by;function Ey(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Fh=Ey;function xy(r){return r[Symbol.asyncIterator]!=null}function vy(r,e){if(xy(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Fh(r),{value:n,done:o}=t.next();if(o===!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 i=e;return function*(){s===!0&&(yield n);for(let a of t)i(a)&&(yield a)}()}var Pr=vy;function Ay(r){return r[Symbol.asyncIterator]!=null}function Ry(r,e){return Ay(r)?async function*(){yield*(await so(r)).sort(e)}():function*(){yield*so(r).sort(e)}()}var jc=Ry;function Iy(r){return r[Symbol.asyncIterator]!=null}function _y(r,e){return Iy(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 Yc=_y;var Zs=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:o}of e)await this.put(n,o,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,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Gc(this.putMany(e,n)),e=[],await Gc(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 o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jc(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=Yc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>jc(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=Yc(n,e.limit)),n}};var $h=dt(Wc(),1);function Hh(r){return r=r??new Error("Not Found"),(0,$h.default)(r,"ERR_NOT_FOUND")}var Js=class extends Zs{data;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 Hh();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 Dr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Dr(e)}};function qh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Cy=r=>r;function Xc(r,e){let t=r.getPeerId();return t!=null&&he(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Qs=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Cy,this._updatePeerStoreAddresses=qh(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])=>se(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=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=Xc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=Xc(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=Xc(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,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Zc=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ls())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>$l(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")}},Ty=["metrics","connectionProtector"],Ny=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function zh(r={}){let e=new Zc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Ny.includes(o)){let i=e.components[o];if(i==null&&!Ty.includes(o))throw new E(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}var Jh=dt(Gh(),1);var jh="[a-fA-F\\d:]",ur=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${jh})|(?<=${jh})(?=\\s|$))`:"",ht="(?: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}",de="[a-fA-F\\d]{1,4}",ei=`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var ep=Object.create;var Ki=Object.defineProperty;var rp=Object.getOwnPropertyDescriptor;var np=Object.getOwnPropertyNames;var ip=Object.getPrototypeOf,op=Object.prototype.hasOwnProperty;var tt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ut=(e,t)=>{for(var r in t)Ki(e,r,{get:t[r],enumerable:!0})},rl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of np(t))!op.call(e,i)&&i!==r&&Ki(e,i,{get:()=>t[i],enumerable:!(n=rp(t,i))||n.enumerable});return e};var St=(e,t,r)=>(r=e!=null?ep(ip(e)):{},rl(t||!e||!e.__esModule?Ki(r,"default",{value:e,enumerable:!0}):r,e)),sp=e=>rl(Ki({},"__esModule",{value:!0}),e);var ft=tt((Gb,nl)=>{nl.exports={options:{usePureJavaScript:!1}}});var sl=tt((Yb,ol)=>{var Vs={};ol.exports=Vs;var il={};Vs.encode=function(e,t,r){if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');if(r!==void 0&&typeof r!="number")throw new TypeError('"maxline" must be a number.');var n="";if(!(e instanceof Uint8Array))n=ap(e,t);else{var i=0,o=t.length,s=t.charAt(0),a=[0];for(i=0;i<e.length;++i){for(var c=0,u=e[i];c<a.length;++c)u+=a[c]<<8,a[c]=u%o,u=u/o|0;for(;u>0;)a.push(u%o),u=u/o|0}for(i=0;e[i]===0&&i<e.length-1;++i)n+=s;for(i=a.length-1;i>=0;--i)n+=t[a[i]]}if(r){var l=new RegExp(".{1,"+r+"}","g");n=n.match(l).join(`\r
|
|
3
|
+
`)}return n};Vs.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var r=il[t];if(!r){r=il[t]=[];for(var n=0;n<t.length;++n)r[t.charCodeAt(n)]=n}e=e.replace(/\s/g,"");for(var i=t.length,o=t.charAt(0),s=[0],n=0;n<e.length;n++){var a=r[e.charCodeAt(n)];if(a===void 0)return;for(var c=0,u=a;c<s.length;++c)u+=s[c]*i,s[c]=u&255,u>>=8;for(;u>0;)s.push(u&255),u>>=8}for(var l=0;e[l]===o&&l<e.length-1;++l)s.push(0);return typeof Buffer<"u"?Buffer.from(s.reverse()):new Uint8Array(s.reverse())};function ap(e,t){var r=0,n=t.length,i=t.charAt(0),o=[0];for(r=0;r<e.length();++r){for(var s=0,a=e.at(r);s<o.length;++s)a+=o[s]<<8,o[s]=a%n,a=a/n|0;for(;a>0;)o.push(a%n),a=a/n|0}var c="";for(r=0;e.at(r)===0&&r<e.length()-1;++r)c+=i;for(r=o.length-1;r>=0;--r)c+=t[o[r]];return c}});var Lt=tt((Wb,ll)=>{var al=ft(),cl=sl(),v=ll.exports=al.util=al.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){v.nextTick=process.nextTick,typeof setImmediate=="function"?v.setImmediate=setImmediate:v.setImmediate=v.nextTick;return}if(typeof setImmediate=="function"){v.setImmediate=function(){return setImmediate.apply(void 0,arguments)},v.nextTick=function(a){return setImmediate(a)};return}if(v.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage=="function"){let a=function(c){if(c.source===window&&c.data===e){c.stopPropagation();var u=t.slice();t.length=0,u.forEach(function(l){l()})}};var s=a,e="forge.setImmediate",t=[];v.setImmediate=function(c){t.push(c),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var r=Date.now(),n=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var c=t.slice();t.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var o=v.setImmediate;v.setImmediate=function(c){Date.now()-r>15?(r=Date.now(),o(c)):(t.push(c),t.length===1&&i.setAttribute("a",n=!n))}}v.nextTick=v.setImmediate})();v.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;v.globalScope=function(){return v.isNodejs?globalThis:typeof self>"u"?window:self}();v.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};v.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};v.isArrayBufferView=function(e){return e&&v.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function ei(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}v.ByteBuffer=qs;function qs(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(v.isArrayBuffer(e)||v.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var r=0;r<t.length;++r)this.putByte(t[r])}}else(e instanceof qs||typeof e=="object"&&typeof e.data=="string"&&typeof e.read=="number")&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}v.ByteStringBuffer=qs;var cp=4096;v.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>cp&&(this.data.substr(0,1),this._constructedStringLength=0)};v.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};v.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};v.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};v.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this};v.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};v.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(v.encodeUtf8(e))};v.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};v.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};v.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};v.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};v.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};v.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};v.ByteStringBuffer.prototype.putInt=function(e,t){ei(t);var r="";do t-=8,r+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(r)};v.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)};v.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};v.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};v.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};v.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};v.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};v.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};v.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};v.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};v.ByteStringBuffer.prototype.getInt=function(e){ei(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};v.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t};v.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};v.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};v.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};v.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};v.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};v.ByteStringBuffer.prototype.copy=function(){var e=v.createBuffer(this.data);return e.read=this.read,e};v.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};v.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};v.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};v.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e};v.ByteStringBuffer.prototype.toString=function(){return v.decodeUtf8(this.bytes())};function up(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=v.isArrayBuffer(e),n=v.isArrayBufferView(e);if(r||n){r?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!=null&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)}v.DataBuffer=up;v.DataBuffer.prototype.length=function(){return this.write-this.read};v.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};v.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this};v.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};v.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this};v.DataBuffer.prototype.putBytes=function(e,t){if(v.isArrayBufferView(e)){var r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=r.byteLength-r.byteOffset;this.accommodate(n);var i=new Uint8Array(this.data.buffer,this.write);return i.set(r),this.write+=n,this}if(v.isArrayBuffer(e)){var r=new Uint8Array(e);this.accommodate(r.byteLength);var i=new Uint8Array(this.data.buffer);return i.set(r,this.write),this.write+=r.byteLength,this}if(e instanceof v.DataBuffer||typeof e=="object"&&typeof e.read=="number"&&typeof e.write=="number"&&v.isArrayBufferView(e.data)){var r=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(r.byteLength);var i=new Uint8Array(e.data.byteLength,this.write);return i.set(r),this.write+=r.byteLength,this}if(e instanceof v.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary",typeof e=="string"){var o;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),o=new Uint8Array(this.data.buffer,this.write),this.write+=v.binary.hex.decode(e,o,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),o=new Uint8Array(this.data.buffer,this.write),this.write+=v.binary.base64.decode(e,o,this.write),this;if(t==="utf8"&&(e=v.encodeUtf8(e),t="binary"),t==="binary"||t==="raw")return this.accommodate(e.length),o=new Uint8Array(this.data.buffer,this.write),this.write+=v.binary.raw.decode(o),this;if(t==="utf16")return this.accommodate(e.length*2),o=new Uint16Array(this.data.buffer,this.write),this.write+=v.text.utf16.encode(o),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};v.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};v.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};v.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};v.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};v.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};v.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};v.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};v.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};v.DataBuffer.prototype.putInt=function(e,t){ei(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};v.DataBuffer.prototype.putSignedInt=function(e,t){return ei(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)};v.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};v.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};v.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};v.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};v.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};v.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};v.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};v.DataBuffer.prototype.getInt=function(e){ei(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};v.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t};v.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};v.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};v.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};v.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};v.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};v.DataBuffer.prototype.copy=function(){return new v.DataBuffer(this)};v.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};v.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};v.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};v.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e};v.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return v.binary.raw.encode(t);if(e==="hex")return v.binary.hex.encode(t);if(e==="base64")return v.binary.base64.encode(t);if(e==="utf8")return v.text.utf8.decode(t);if(e==="utf16")return v.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)};v.createBuffer=function(e,t){return t=t||"raw",e!==void 0&&t==="utf8"&&(e=v.encodeUtf8(e)),new v.ByteBuffer(e)};v.fillString=function(e,t){for(var r="";t>0;)t&1&&(r+=e),t>>>=1,t>0&&(e+=e);return r};v.xorBytes=function(e,t,r){for(var n="",i="",o="",s=0,a=0;r>0;--r,++s)i=e.charCodeAt(s)^t.charCodeAt(s),a>=10&&(n+=o,o="",a=0),o+=String.fromCharCode(i),++a;return n+=o,n};v.hexToBytes=function(e){var t="",r=0;for(e.length&!0&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t};v.bytesToHex=function(e){return v.createBuffer(e).toHex()};v.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",lr=[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],ul="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";v.encode64=function(e,t){for(var r="",n="",i,o,s,a=0;a<e.length;)i=e.charCodeAt(a++),o=e.charCodeAt(a++),s=e.charCodeAt(a++),r+=ur.charAt(i>>2),r+=ur.charAt((i&3)<<4|o>>4),isNaN(o)?r+="==":(r+=ur.charAt((o&15)<<2|s>>6),r+=isNaN(s)?"=":ur.charAt(s&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r
|
|
4
|
+
`,r=r.substr(t));return n+=r,n};v.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",r,n,i,o,s=0;s<e.length;)r=lr[e.charCodeAt(s++)-43],n=lr[e.charCodeAt(s++)-43],i=lr[e.charCodeAt(s++)-43],o=lr[e.charCodeAt(s++)-43],t+=String.fromCharCode(r<<2|n>>4),i!==64&&(t+=String.fromCharCode((n&15)<<4|i>>2),o!==64&&(t+=String.fromCharCode((i&3)<<6|o)));return t};v.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};v.decodeUtf8=function(e){return decodeURIComponent(escape(e))};v.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:cl.encode,decode:cl.decode}};v.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};v.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var i=r,o=0;o<e.length;++o)n[i++]=e.charCodeAt(o);return t?i-r:n};v.binary.hex.encode=v.bytesToHex;v.binary.hex.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/2))),r=r||0;var i=0,o=r;for(e.length&1&&(i=1,n[o++]=parseInt(e[0],16));i<e.length;i+=2)n[o++]=parseInt(e.substr(i,2),16);return t?o-r:n};v.binary.base64.encode=function(e,t){for(var r="",n="",i,o,s,a=0;a<e.byteLength;)i=e[a++],o=e[a++],s=e[a++],r+=ur.charAt(i>>2),r+=ur.charAt((i&3)<<4|o>>4),isNaN(o)?r+="==":(r+=ur.charAt((o&15)<<2|s>>6),r+=isNaN(s)?"=":ur.charAt(s&63)),t&&r.length>t&&(n+=r.substr(0,t)+`\r
|
|
5
|
+
`,r=r.substr(t));return n+=r,n};v.binary.base64.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var i,o,s,a,c=0,u=r;c<e.length;)i=lr[e.charCodeAt(c++)-43],o=lr[e.charCodeAt(c++)-43],s=lr[e.charCodeAt(c++)-43],a=lr[e.charCodeAt(c++)-43],n[u++]=i<<2|o>>4,s!==64&&(n[u++]=(o&15)<<4|s>>2,a!==64&&(n[u++]=(s&3)<<6|a));return t?u-r:n.subarray(0,u)};v.binary.base58.encode=function(e,t){return v.binary.baseN.encode(e,ul,t)};v.binary.base58.decode=function(e,t){return v.binary.baseN.decode(e,ul,t)};v.text={utf8:{},utf16:{}};v.text.utf8.encode=function(e,t,r){e=v.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var i=r,o=0;o<e.length;++o)n[i++]=e.charCodeAt(o);return t?i-r:n};v.text.utf8.decode=function(e){return v.decodeUtf8(String.fromCharCode.apply(null,e))};v.text.utf16.encode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length*2));var i=new Uint16Array(n.buffer);r=r||0;for(var o=r,s=r,a=0;a<e.length;++a)i[s++]=e.charCodeAt(a),o+=2;return t?o-r:n};v.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};v.deflate=function(e,t,r){if(t=v.decode64(e.deflate(v.encode64(t)).rval),r){var n=2,i=t.charCodeAt(1);i&32&&(n=6),t=t.substring(n,t.length-4)}return t};v.inflate=function(e,t,r){var n=e.inflate(v.encode64(t)).rval;return n===null?null:v.decode64(n)};var zs=function(e,t,r){if(!e)throw new Error("WebStorage not available.");var n;if(r===null?n=e.removeItem(t):(r=v.encode64(JSON.stringify(r)),n=e.setItem(t,r)),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}},$s=function(e,t){if(!e)throw new Error("WebStorage not available.");var r=e.getItem(t);if(e.init)if(r.rval===null){if(r.error){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}r=null}else r=r.rval;return r!==null&&(r=JSON.parse(v.decode64(r))),r},lp=function(e,t,r,n){var i=$s(e,t);i===null&&(i={}),i[r]=n,zs(e,t,i)},fp=function(e,t,r){var n=$s(e,t);return n!==null&&(n=r in n?n[r]:null),n},hp=function(e,t,r){var n=$s(e,t);if(n!==null&&r in n){delete n[r];var i=!0;for(var o in n){i=!1;break}i&&(n=null),zs(e,t,n)}},dp=function(e,t){zs(e,t,null)},Vi=function(e,t,r){var n=null;typeof r>"u"&&(r=["web","flash"]);var i,o=!1,s=null;for(var a in r){i=r[a];try{if(i==="flash"||i==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");n=e.apply(this,t),o=i==="flash"}(i==="web"||i==="both")&&(t[0]=localStorage,n=e.apply(this,t),o=!0)}catch(c){s=c}if(o)break}if(!o)throw s;return n};v.setItem=function(e,t,r,n,i){Vi(lp,arguments,i)};v.getItem=function(e,t,r,n){return Vi(fp,arguments,n)};v.removeItem=function(e,t,r,n){Vi(hp,arguments,n)};v.clearItems=function(e,t,r){Vi(dp,arguments,r)};v.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};v.format=function(e){for(var t=/%./g,r,n,i=0,o=[],s=0;r=t.exec(e);){n=e.substring(s,t.lastIndex-2),n.length>0&&o.push(n),s=t.lastIndex;var a=r[0][1];switch(a){case"s":case"o":i<arguments.length?o.push(arguments[i+++1]):o.push("<?>");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(e.substring(s)),o.join("")};v.formatNumber=function(e,t,r,n){var i=e,o=isNaN(t=Math.abs(t))?2:t,s=r===void 0?",":r,a=n===void 0?".":n,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")};v.formatSize=function(e){return e>=1073741824?e=v.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=v.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=v.formatNumber(e/1024,0)+" KiB":e=v.formatNumber(e,0)+" bytes",e};v.bytesFromIP=function(e){return e.indexOf(".")!==-1?v.bytesFromIPv4(e):e.indexOf(":")!==-1?v.bytesFromIPv6(e):null};v.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=v.createBuffer(),r=0;r<e.length;++r){var n=parseInt(e[r],10);if(isNaN(n))return null;t.putByte(n)}return t.getBytes()};v.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(s){return s.length===0&&++t,!0});for(var r=(8-e.length+t)*2,n=v.createBuffer(),i=0;i<8;++i){if(!e[i]||e[i].length===0){n.fillWithByte(0,r),r=0;continue}var o=v.hexToBytes(e[i]);o.length<2&&n.putByte(0),n.putBytes(o)}return n.getBytes()};v.bytesToIP=function(e){return e.length===4?v.bytesToIPv4(e):e.length===16?v.bytesToIPv6(e):null};v.bytesToIPv4=function(e){if(e.length!==4)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")};v.bytesToIPv6=function(e){if(e.length!==16)return null;for(var t=[],r=[],n=0,i=0;i<e.length;i+=2){for(var o=v.bytesToHex(e[i]+e[i+1]);o[0]==="0"&&o!=="0";)o=o.substr(1);if(o==="0"){var s=r[r.length-1],a=t.length;!s||a!==s.end+1?r.push({start:a,end:a}):(s.end=a,s.end-s.start>r[n].end-r[n].start&&(n=r.length-1))}t.push(o)}if(r.length>0){var c=r[n];c.end-c.start>0&&(t.splice(c.start,c.end-c.start+1,""),c.start===0&&t.unshift(""),c.end===7&&t.push(""))}return t.join(":")};v.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in v&&!e.update)return t(null,v.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return v.cores=navigator.hardwareConcurrency,t(null,v.cores);if(typeof Worker>"u")return v.cores=1,t(null,v.cores);if(typeof Blob>"u")return v.cores=2,t(null,v.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){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(s,a,c){if(a===0){var u=Math.floor(s.reduce(function(l,f){return l+f},0)/s.length);return v.cores=Math.max(1,u),URL.revokeObjectURL(r),t(null,v.cores)}i(c,function(l,f){s.push(o(c,f)),n(s,a-1,c)})}function i(s,a){for(var c=[],u=[],l=0;l<s;++l){var f=new Worker(r);f.addEventListener("message",function(d){if(u.push(d.data),u.length===s){for(var p=0;p<s;++p)c[p].terminate();a(null,u)}}),c.push(f)}for(var l=0;l<s;++l)c[l].postMessage(l)}function o(s,a){for(var c=[],u=0;u<s;++u)for(var l=a[u],f=c[u]=[],d=0;d<s;++d)if(u!==d){var p=a[d];(l.st>p.st&&l.st<p.et||p.st>l.st&&p.st<l.et)&&f.push(d)}return c.reduce(function(h,m){return Math.max(h,m.length)},0)}}});var qi=tt((Qb,fl)=>{var ri=ft();ri.pki=ri.pki||{};var Hs=fl.exports=ri.pki.oids=ri.oids=ri.oids||{};function B(e,t){Hs[e]=t,Hs[t]=e}function st(e,t){Hs[e]=t}B("1.2.840.113549.1.1.1","rsaEncryption");B("1.2.840.113549.1.1.4","md5WithRSAEncryption");B("1.2.840.113549.1.1.5","sha1WithRSAEncryption");B("1.2.840.113549.1.1.7","RSAES-OAEP");B("1.2.840.113549.1.1.8","mgf1");B("1.2.840.113549.1.1.9","pSpecified");B("1.2.840.113549.1.1.10","RSASSA-PSS");B("1.2.840.113549.1.1.11","sha256WithRSAEncryption");B("1.2.840.113549.1.1.12","sha384WithRSAEncryption");B("1.2.840.113549.1.1.13","sha512WithRSAEncryption");B("1.3.101.112","EdDSA25519");B("1.2.840.10040.4.3","dsa-with-sha1");B("1.3.14.3.2.7","desCBC");B("1.3.14.3.2.26","sha1");B("1.3.14.3.2.29","sha1WithRSASignature");B("2.16.840.1.101.3.4.2.1","sha256");B("2.16.840.1.101.3.4.2.2","sha384");B("2.16.840.1.101.3.4.2.3","sha512");B("2.16.840.1.101.3.4.2.4","sha224");B("2.16.840.1.101.3.4.2.5","sha512-224");B("2.16.840.1.101.3.4.2.6","sha512-256");B("1.2.840.113549.2.2","md2");B("1.2.840.113549.2.5","md5");B("1.2.840.113549.1.7.1","data");B("1.2.840.113549.1.7.2","signedData");B("1.2.840.113549.1.7.3","envelopedData");B("1.2.840.113549.1.7.4","signedAndEnvelopedData");B("1.2.840.113549.1.7.5","digestedData");B("1.2.840.113549.1.7.6","encryptedData");B("1.2.840.113549.1.9.1","emailAddress");B("1.2.840.113549.1.9.2","unstructuredName");B("1.2.840.113549.1.9.3","contentType");B("1.2.840.113549.1.9.4","messageDigest");B("1.2.840.113549.1.9.5","signingTime");B("1.2.840.113549.1.9.6","counterSignature");B("1.2.840.113549.1.9.7","challengePassword");B("1.2.840.113549.1.9.8","unstructuredAddress");B("1.2.840.113549.1.9.14","extensionRequest");B("1.2.840.113549.1.9.20","friendlyName");B("1.2.840.113549.1.9.21","localKeyId");B("1.2.840.113549.1.9.22.1","x509Certificate");B("1.2.840.113549.1.12.10.1.1","keyBag");B("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");B("1.2.840.113549.1.12.10.1.3","certBag");B("1.2.840.113549.1.12.10.1.4","crlBag");B("1.2.840.113549.1.12.10.1.5","secretBag");B("1.2.840.113549.1.12.10.1.6","safeContentsBag");B("1.2.840.113549.1.5.13","pkcs5PBES2");B("1.2.840.113549.1.5.12","pkcs5PBKDF2");B("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");B("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");B("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");B("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");B("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");B("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");B("1.2.840.113549.2.7","hmacWithSHA1");B("1.2.840.113549.2.8","hmacWithSHA224");B("1.2.840.113549.2.9","hmacWithSHA256");B("1.2.840.113549.2.10","hmacWithSHA384");B("1.2.840.113549.2.11","hmacWithSHA512");B("1.2.840.113549.3.7","des-EDE3-CBC");B("2.16.840.1.101.3.4.1.2","aes128-CBC");B("2.16.840.1.101.3.4.1.22","aes192-CBC");B("2.16.840.1.101.3.4.1.42","aes256-CBC");B("2.5.4.3","commonName");B("2.5.4.4","surname");B("2.5.4.5","serialNumber");B("2.5.4.6","countryName");B("2.5.4.7","localityName");B("2.5.4.8","stateOrProvinceName");B("2.5.4.9","streetAddress");B("2.5.4.10","organizationName");B("2.5.4.11","organizationalUnitName");B("2.5.4.12","title");B("2.5.4.13","description");B("2.5.4.15","businessCategory");B("2.5.4.17","postalCode");B("2.5.4.42","givenName");B("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");B("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");B("2.16.840.1.113730.1.1","nsCertType");B("2.16.840.1.113730.1.13","nsComment");st("2.5.29.1","authorityKeyIdentifier");st("2.5.29.2","keyAttributes");st("2.5.29.3","certificatePolicies");st("2.5.29.4","keyUsageRestriction");st("2.5.29.5","policyMapping");st("2.5.29.6","subtreesConstraint");st("2.5.29.7","subjectAltName");st("2.5.29.8","issuerAltName");st("2.5.29.9","subjectDirectoryAttributes");st("2.5.29.10","basicConstraints");st("2.5.29.11","nameConstraints");st("2.5.29.12","policyConstraints");st("2.5.29.13","basicConstraints");B("2.5.29.14","subjectKeyIdentifier");B("2.5.29.15","keyUsage");st("2.5.29.16","privateKeyUsagePeriod");B("2.5.29.17","subjectAltName");B("2.5.29.18","issuerAltName");B("2.5.29.19","basicConstraints");st("2.5.29.20","cRLNumber");st("2.5.29.21","cRLReason");st("2.5.29.22","expirationDate");st("2.5.29.23","instructionCode");st("2.5.29.24","invalidityDate");st("2.5.29.25","cRLDistributionPoints");st("2.5.29.26","issuingDistributionPoint");st("2.5.29.27","deltaCRLIndicator");st("2.5.29.28","issuingDistributionPoint");st("2.5.29.29","certificateIssuer");st("2.5.29.30","nameConstraints");B("2.5.29.31","cRLDistributionPoints");B("2.5.29.32","certificatePolicies");st("2.5.29.33","policyMappings");st("2.5.29.34","policyConstraints");B("2.5.29.35","authorityKeyIdentifier");st("2.5.29.36","policyConstraints");B("2.5.29.37","extKeyUsage");st("2.5.29.46","freshestCRL");st("2.5.29.54","inhibitAnyPolicy");B("1.3.6.1.4.1.11129.2.4.2","timestampList");B("1.3.6.1.5.5.7.1.1","authorityInfoAccess");B("1.3.6.1.5.5.7.3.1","serverAuth");B("1.3.6.1.5.5.7.3.2","clientAuth");B("1.3.6.1.5.5.7.3.3","codeSigning");B("1.3.6.1.5.5.7.3.4","emailProtection");B("1.3.6.1.5.5.7.3.8","timeStamping")});var ii=tt((Xb,dl)=>{var pt=ft();Lt();qi();var k=dl.exports=pt.asn1=pt.asn1||{};k.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};k.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};k.create=function(e,t,r,n,i){if(pt.util.isArray(n)){for(var o=[],s=0;s<n.length;++s)n[s]!==void 0&&o.push(n[s]);n=o}var a={tagClass:e,type:t,constructed:r,composed:r||pt.util.isArray(n),value:n};return i&&"bitStringContents"in i&&(a.bitStringContents=i.bitStringContents,a.original=k.copy(a)),a};k.copy=function(e,t){var r;if(pt.util.isArray(e)){r=[];for(var n=0;n<e.length;++n)r.push(k.copy(e[n],t));return r}return typeof e=="string"?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:k.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)};k.equals=function(e,t,r){if(pt.util.isArray(e)){if(!pt.util.isArray(t)||e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(!k.equals(e[n],t[n]))return!1;return!0}if(typeof e!=typeof t)return!1;if(typeof e=="string")return e===t;var i=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&k.equals(e.value,t.value);return r&&r.includeBitStringContents&&(i=i&&e.bitStringContents===t.bitStringContents),i};k.getBerValueLength=function(e){var t=e.getByte();if(t!==128){var r,n=t&128;return n?r=e.getInt((t&127)<<3):r=t,r}};function ni(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}var pp=function(e,t){var r=e.getByte();if(t--,r!==128){var n,i=r&128;if(!i)n=r;else{var o=r&127;ni(e,t,o),n=e.getInt(o<<3)}if(n<0)throw new Error("Negative length: "+n);return n}};k.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),typeof e=="string"&&(e=pt.util.createBuffer(e));var r=e.length(),n=zi(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=r,i.remaining=e.length(),i}return n};function zi(e,t,r,n){var i;ni(e,t,2);var o=e.getByte();t--;var s=o&192,a=o&31;i=e.length();var c=pp(e,t);if(t-=i-e.length(),c!==void 0&&c>t){if(n.strict){var u=new Error("Too few bytes to read ASN.1 value.");throw u.available=e.length(),u.remaining=t,u.requested=c,u}c=t}var l,f,d=(o&32)===32;if(d)if(l=[],c===void 0)for(;;){if(ni(e,t,2),e.bytes(2)==="\0\0"){e.getBytes(2),t-=2;break}i=e.length(),l.push(zi(e,t,r+1,n)),t-=i-e.length()}else for(;c>0;)i=e.length(),l.push(zi(e,c,r+1,n)),t-=i-e.length(),c-=i-e.length();if(l===void 0&&s===k.Class.UNIVERSAL&&a===k.Type.BITSTRING&&(f=e.bytes(c)),l===void 0&&n.decodeBitStrings&&s===k.Class.UNIVERSAL&&a===k.Type.BITSTRING&&c>1){var p=e.read,h=t,m=0;if(a===k.Type.BITSTRING&&(ni(e,t,1),m=e.getByte(),t--),m===0)try{i=e.length();var g={strict:!0,decodeBitStrings:!0},y=zi(e,t,r+1,g),x=i-e.length();t-=x,a==k.Type.BITSTRING&&x++;var b=y.tagClass;x===c&&(b===k.Class.UNIVERSAL||b===k.Class.CONTEXT_SPECIFIC)&&(l=[y])}catch{}l===void 0&&(e.read=p,t=h)}if(l===void 0){if(c===void 0){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=t}if(a===k.Type.BMPSTRING)for(l="";c>0;c-=2)ni(e,t,2),l+=String.fromCharCode(e.getInt16()),t-=2;else l=e.getBytes(c),t-=c}var _=f===void 0?null:{bitStringContents:f};return k.create(s,a,d,l,_)}k.toDer=function(e){var t=pt.util.createBuffer(),r=e.tagClass|e.type,n=pt.util.createBuffer(),i=!1;if("bitStringContents"in e&&(i=!0,e.original&&(i=k.equals(e,e.original))),i)n.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:n.putByte(0);for(var o=0;o<e.value.length;++o)e.value[o]!==void 0&&n.putBuffer(k.toDer(e.value[o]))}else if(e.type===k.Type.BMPSTRING)for(var o=0;o<e.value.length;++o)n.putInt16(e.value.charCodeAt(o));else e.type===k.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&!(e.value.charCodeAt(1)&128)||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?n.putBytes(e.value.substr(1)):n.putBytes(e.value);if(t.putByte(r),n.length()<=127)t.putByte(n.length()&127);else{var s=n.length(),a="";do a+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)t.putByte(a.charCodeAt(o))}return t.putBuffer(n),t};k.oidToDer=function(e){var t=e.split("."),r=pt.util.createBuffer();r.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var n,i,o,s,a=2;a<t.length;++a){n=!0,i=[],o=parseInt(t[a],10);do s=o&127,o=o>>>7,n||(s|=128),i.push(s),n=!1;while(o>0);for(var c=i.length-1;c>=0;--c)r.putByte(i[c])}return r};k.derToOid=function(e){var t;typeof e=="string"&&(e=pt.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;)r=e.getByte(),n=n<<7,r&128?n+=r&127:(t+="."+(n+r),n=0);return t};k.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),o=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),u=10;c!=="+"&&c!=="-"&&(a=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,0),u&&(c=e.charAt(u),c==="+"||c==="-")){var l=parseInt(e.substr(u+1,2),10),f=parseInt(e.substr(u+4,2),10),d=l*60+f;d*=6e4,c==="+"?t.setTime(+t-d):t.setTime(+t+d)}return t};k.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;e.charAt(e.length-1)==="Z"&&(l=!0);var f=e.length-5,d=e.charAt(f);if(d==="+"||d==="-"){var p=parseInt(e.substr(f+1,2),10),h=parseInt(e.substr(f+4,2),10);u=p*60+h,u*=6e4,d==="+"&&(u*=-1),l=!0}return e.charAt(14)==="."&&(c=parseFloat(e.substr(14),10)*1e3),l?(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,c),t.setTime(+t+u)):(t.setFullYear(r,n,i),t.setHours(o,s,a,c)),t};k.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z",t};k.dateToGeneralizedTime=function(e){if(typeof e=="string")return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z",t};k.integerToDer=function(e){var t=pt.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r};k.derToInteger=function(e){typeof e=="string"&&(e=pt.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};k.validate=function(e,t,r,n){var i=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(i=!0,t.value&&pt.util.isArray(t.value))for(var o=0,s=0;i&&s<t.value.length;++s)i=t.value[s].optional||!1,e.value[o]&&(i=k.validate(e.value[o],t.value[s],r,n),i?++o:t.value[s].optional&&(i=!0)),!i&&n&&n.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(i&&r&&(t.capture&&(r[t.capture]=e.value),t.captureAsn1&&(r[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(r[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e)){var a;if(e.bitStringContents.length<2)r[t.captureBitStringValue]="";else{var c=e.bitStringContents.charCodeAt(0);if(c!==0)throw new Error("captureBitStringValue only supported for zero unused bits");r[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}else n&&n.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');else n&&(e.tagClass!==t.tagClass&&n.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&n.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return i};var hl=/[^\\u0000-\\u00ff]/;k.prettyPrint=function(e,t,r){var n="";t=t||0,r=r||2,t>0&&(n+=`
|
|
6
|
+
`);for(var i="",o=0;o<t*r;++o)i+=" ";switch(n+=i+"Tag: ",e.tagClass){case k.Class.UNIVERSAL:n+="Universal:";break;case k.Class.APPLICATION:n+="Application:";break;case k.Class.CONTEXT_SPECIFIC:n+="Context-Specific:";break;case k.Class.PRIVATE:n+="Private:";break}if(e.tagClass===k.Class.UNIVERSAL)switch(n+=e.type,e.type){case k.Type.NONE:n+=" (None)";break;case k.Type.BOOLEAN:n+=" (Boolean)";break;case k.Type.INTEGER:n+=" (Integer)";break;case k.Type.BITSTRING:n+=" (Bit string)";break;case k.Type.OCTETSTRING:n+=" (Octet string)";break;case k.Type.NULL:n+=" (Null)";break;case k.Type.OID:n+=" (Object Identifier)";break;case k.Type.ODESC:n+=" (Object Descriptor)";break;case k.Type.EXTERNAL:n+=" (External or Instance of)";break;case k.Type.REAL:n+=" (Real)";break;case k.Type.ENUMERATED:n+=" (Enumerated)";break;case k.Type.EMBEDDED:n+=" (Embedded PDV)";break;case k.Type.UTF8:n+=" (UTF8)";break;case k.Type.ROID:n+=" (Relative Object Identifier)";break;case k.Type.SEQUENCE:n+=" (Sequence)";break;case k.Type.SET:n+=" (Set)";break;case k.Type.PRINTABLESTRING:n+=" (Printable String)";break;case k.Type.IA5String:n+=" (IA5String (ASCII))";break;case k.Type.UTCTIME:n+=" (UTC time)";break;case k.Type.GENERALIZEDTIME:n+=" (Generalized time)";break;case k.Type.BMPSTRING:n+=" (BMP String)";break}else n+=e.type;if(n+=`
|
|
7
|
+
`,n+=i+"Constructed: "+e.constructed+`
|
|
8
|
+
`,e.composed){for(var s=0,a="",o=0;o<e.value.length;++o)e.value[o]!==void 0&&(s+=1,a+=k.prettyPrint(e.value[o],t+1,r),o+1<e.value.length&&(a+=","));n+=i+"Sub values: "+s+a}else{if(n+=i+"Value: ",e.type===k.Type.OID){var c=k.derToOid(e.value);n+=c,pt.pki&&pt.pki.oids&&c in pt.pki.oids&&(n+=" ("+pt.pki.oids[c]+") ")}if(e.type===k.Type.INTEGER)try{n+=k.derToInteger(e.value)}catch{n+="0x"+pt.util.bytesToHex(e.value)}else if(e.type===k.Type.BITSTRING){if(e.value.length>1?n+="0x"+pt.util.bytesToHex(e.value.slice(1)):n+="(none)",e.value.length>0){var u=e.value.charCodeAt(0);u==1?n+=" (1 unused bit shown)":u>1&&(n+=" ("+u+" unused bits shown)")}}else if(e.type===k.Type.OCTETSTRING)hl.test(e.value)||(n+="("+e.value+") "),n+="0x"+pt.util.bytesToHex(e.value);else if(e.type===k.Type.UTF8)try{n+=pt.util.decodeUtf8(e.value)}catch(l){if(l.message==="URI malformed")n+="0x"+pt.util.bytesToHex(e.value)+" (malformed UTF8)";else throw l}else e.type===k.Type.PRINTABLESTRING||e.type===k.Type.IA5String?n+=e.value:hl.test(e.value)?n+="0x"+pt.util.bytesToHex(e.value):e.value.length===0?n+="[null]":n+=e.value}return n}});var Ys=tt((Zb,pl)=>{var Ft=ft();Lt();pl.exports=Ft.cipher=Ft.cipher||{};Ft.cipher.algorithms=Ft.cipher.algorithms||{};Ft.cipher.createCipher=function(e,t){var r=e;if(typeof r=="string"&&(r=Ft.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+e);return new Ft.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})};Ft.cipher.createDecipher=function(e,t){var r=e;if(typeof r=="string"&&(r=Ft.cipher.getAlgorithm(r),r&&(r=r())),!r)throw new Error("Unsupported algorithm: "+e);return new Ft.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})};Ft.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),Ft.cipher.algorithms[e]=t};Ft.cipher.getAlgorithm=function(e){return e=e.toUpperCase(),e in Ft.cipher.algorithms?Ft.cipher.algorithms[e]:null};var Gs=Ft.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};Gs.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=Ft.util.createBuffer(),this.output=e.output||Ft.util.createBuffer(),this.mode.start(t)};Gs.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};Gs.prototype.finish=function(e){e&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(r){return e(this.blockSize,r,!1)},this.mode.unpad=function(r){return e(this.blockSize,r,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t))}});var Qs=tt((Jb,ml)=>{var Kt=ft();Lt();Kt.cipher=Kt.cipher||{};var Z=ml.exports=Kt.cipher.modes=Kt.cipher.modes||{};Z.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Z.ecb.prototype.start=function(e){};Z.ecb.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])};Z.ecb.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])};Z.ecb.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0};Z.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return n>this.blockSize<<2?!1:(e.truncate(n),!0)};Z.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};Z.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=$i(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};Z.cbc.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=this._prev[n]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]);this._prev=this._outBlock};Z.cbc.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._prev[n]^this._outBlock[n]);this._prev=this._inBlock.slice(0)};Z.cbc.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0};Z.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return n>this.blockSize<<2?!1:(e.truncate(n),!0)};Z.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=Kt.util.createBuffer(),this._partialBytes=0};Z.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=$i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Z.cfb.prototype.encrypt=function(e,t,r){var n=e.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]=e.getInt32()^this._outBlock[i],t.putInt32(this._inBlock[i]);return}var o=(this.blockSize-n)%this.blockSize;o>0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32()^this._outBlock[i],this._partialOutput.putInt32(this._partialBlock[i]);if(o>0)e.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),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Z.cfb.prototype.decrypt=function(e,t,r){var n=e.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]=e.getInt32(),t.putInt32(this._inBlock[i]^this._outBlock[i]);return}var o=(this.blockSize-n)%this.blockSize;o>0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[i]^this._outBlock[i]);if(o>0)e.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),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Z.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Kt.util.createBuffer(),this._partialBytes=0};Z.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=$i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Z.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(e.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)t.putInt32(e.getInt32()^this._outBlock[i]),this._inBlock[i]=this._outBlock[i];return}var o=(this.blockSize-n)%this.blockSize;o>0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>0)e.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),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0};Z.ofb.prototype.decrypt=Z.ofb.prototype.encrypt;Z.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Kt.util.createBuffer(),this._partialBytes=0};Z.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=$i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};Z.ctr.prototype.encrypt=function(e,t,r){var n=e.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)t.putInt32(e.getInt32()^this._outBlock[i]);else{var o=(this.blockSize-n)%this.blockSize;o>0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}Hi(this._inBlock)};Z.ctr.prototype.decrypt=Z.ctr.prototype.encrypt;Z.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=Kt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};Z.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=Kt.util.createBuffer(e.iv);this._cipherLength=0;var r;if("additionalData"in e?r=Kt.util.createBuffer(e.additionalData):r=Kt.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=Kt.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=t.length();if(n===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(Ws(n*8)))}this._inBlock=this._j0.slice(0),Hi(this._inBlock),this._partialBytes=0,r=Kt.util.createBuffer(r),this._aDataLength=Ws(r.length()*8);var i=r.length()%this.blockSize;for(i&&r.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];r.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()])};Z.gcm.prototype.encrypt=function(e,t,r){var n=e.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)t.putInt32(this._outBlock[i]^=e.getInt32());this._cipherLength+=this.blockSize}else{var o=(this.blockSize-n)%this.blockSize;o>0&&(o=this.blockSize-o),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o<=0||r){if(r){var s=n%this.blockSize;this._cipherLength+=s,this._partialOutput.truncate(this.blockSize-s)}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),o>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Hi(this._inBlock)};Z.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n<this.blockSize&&!(r&&n>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),Hi(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i<this._ints;++i)t.putInt32(this._outBlock[i]^this._hashBlock[i]);n<this.blockSize?this._cipherLength+=n%this.blockSize:this._cipherLength+=this.blockSize};Z.gcm.prototype.afterFinish=function(e,t){var r=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=Kt.util.createBuffer();var n=this._aDataLength.concat(Ws(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,n);var i=[];this.cipher.encrypt(this._j0,i);for(var o=0;o<this._ints;++o)this.tag.putInt32(this._s[o]^i[o]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(r=!1),r};Z.gcm.prototype.multiply=function(e,t){for(var r=[0,0,0,0],n=t.slice(0),i=0;i<128;++i){var o=e[i/32|0]&1<<31-i%32;o&&(r[0]^=n[0],r[1]^=n[1],r[2]^=n[2],r[3]^=n[3]),this.pow(n,n)}return r};Z.gcm.prototype.pow=function(e,t){for(var r=e[3]&1,n=3;n>0;--n)t[n]=e[n]>>>1|(e[n-1]&1)<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)};Z.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=r/8|0,i=e[n]>>>(7-r%8)*4&15,o=this._m[r][i];t[0]^=o[0],t[1]^=o[1],t[2]^=o[2],t[3]^=o[3]}return t};Z.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)};Z.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,o=new Array(i),s=0;s<i;++s){var a=[0,0,0,0],c=s/n|0,u=(n-1-s%n)*t;a[c]=1<<t-1<<u,o[s]=this.generateSubHashTable(this.multiply(a,e),t)}return o};Z.gcm.prototype.generateSubHashTable=function(e,t){var r=1<<t,n=r>>>1,i=new Array(r);i[n]=e.slice(0);for(var o=n>>>1;o>0;)this.pow(i[2*o],i[o]=[]),o>>=1;for(o=2;o<n;){for(var s=1;s<o;++s){var a=i[o],c=i[s];i[o+s]=[a[0]^c[0],a[1]^c[1],a[2]^c[2],a[3]^c[3]]}o*=2}for(i[0]=[0,0,0,0],o=n+1;o<r;++o){var u=i[o^n];i[o]=[e[0]^u[0],e[1]^u[1],e[2]^u[2],e[3]^u[3]]}return i};function $i(e,t){if(typeof e=="string"&&(e=Kt.util.createBuffer(e)),Kt.util.isArray(e)&&e.length>4){var r=e;e=Kt.util.createBuffer();for(var n=0;n<r.length;++n)e.putByte(r[n])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!Kt.util.isArray(e)){for(var i=[],o=t/4,n=0;n<o;++n)i.push(e.getInt32());e=i}return e}function Hi(e){e[e.length-1]=e[e.length-1]+1&4294967295}function Ws(e){return[e/4294967296|0,e&4294967295]}});var js=tt((jb,bl)=>{var dt=ft();Ys();Qs();Lt();bl.exports=dt.aes=dt.aes||{};dt.aes.startEncrypting=function(e,t,r,n){var i=Gi({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i};dt.aes.createEncryptionCipher=function(e,t){return Gi({key:e,output:null,decrypt:!1,mode:t})};dt.aes.startDecrypting=function(e,t,r,n){var i=Gi({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i};dt.aes.createDecryptionCipher=function(e,t){return Gi({key:e,output:null,decrypt:!0,mode:t})};dt.aes.Algorithm=function(e,t){Js||yl();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(n,i){return Zs(r._w,n,i,!1)},decrypt:function(n,i){return Zs(r._w,n,i,!0)}}}),r._init=!1};dt.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t=e.key,r;if(typeof t=="string"&&(t.length===16||t.length===24||t.length===32))t=dt.util.createBuffer(t);else if(dt.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){r=t,t=dt.util.createBuffer();for(var n=0;n<r.length;++n)t.putByte(r[n])}if(!dt.util.isArray(t)){r=t,t=[];var i=r.length();if(i===16||i===24||i===32){i=i>>>2;for(var n=0;n<i;++n)t.push(r.getInt32())}}if(!dt.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw new Error("Invalid key parameter.");var o=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(o)!==-1;this._w=xl(t,e.decrypt&&!s),this._init=!0}};dt.aes._expandKey=function(e,t){return Js||yl(),xl(e,t)};dt.aes._updateBlock=Zs;mn("AES-ECB",dt.cipher.modes.ecb);mn("AES-CBC",dt.cipher.modes.cbc);mn("AES-CFB",dt.cipher.modes.cfb);mn("AES-OFB",dt.cipher.modes.ofb);mn("AES-CTR",dt.cipher.modes.ctr);mn("AES-GCM",dt.cipher.modes.gcm);function mn(e,t){var r=function(){return new dt.aes.Algorithm(e,t)};dt.cipher.registerAlgorithm(e,r)}var Js=!1,pn=4,ie,Xs,gl,Nr,Ae;function yl(){Js=!0,gl=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;ie=new Array(256),Xs=new Array(256),Nr=new Array(4),Ae=new Array(4);for(var t=0;t<4;++t)Nr[t]=new Array(256),Ae[t]=new Array(256);for(var r=0,n=0,i,o,s,a,c,u,l,t=0;t<256;++t){a=n^n<<1^n<<2^n<<3^n<<4,a=a>>8^a&255^99,ie[r]=a,Xs[a]=r,c=e[a],i=e[r],o=e[i],s=e[o],u=c<<24^a<<16^a<<8^(a^c),l=(i^o^s)<<24^(r^s)<<16^(r^o^s)<<8^(r^i^s);for(var f=0;f<4;++f)Nr[f][r]=u,Ae[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;r===0?r=n=1:(r=i^e[e[e[i^s]]],n^=e[e[n]])}}function xl(e,t){for(var r=e.slice(0),n,i=1,o=r.length,s=o+6+1,a=pn*s,c=o;c<a;++c)n=r[c-1],c%o===0?(n=ie[n>>>16&255]<<24^ie[n>>>8&255]<<16^ie[n&255]<<8^ie[n>>>24]^gl[i]<<24,i++):o>6&&c%o===4&&(n=ie[n>>>24]<<24^ie[n>>>16&255]<<16^ie[n>>>8&255]<<8^ie[n&255]),r[c]=r[c-o]^n;if(t){var u,l=Ae[0],f=Ae[1],d=Ae[2],p=Ae[3],h=r.slice(0);a=r.length;for(var c=0,m=a-pn;c<a;c+=pn,m-=pn)if(c===0||c===a-pn)h[c]=r[m],h[c+1]=r[m+3],h[c+2]=r[m+2],h[c+3]=r[m+1];else for(var g=0;g<pn;++g)u=r[m+g],h[c+(3&-g)]=l[ie[u>>>24]]^f[ie[u>>>16&255]]^d[ie[u>>>8&255]]^p[ie[u&255]];r=h}return r}function Zs(e,t,r,n){var i=e.length/4-1,o,s,a,c,u;n?(o=Ae[0],s=Ae[1],a=Ae[2],c=Ae[3],u=Xs):(o=Nr[0],s=Nr[1],a=Nr[2],c=Nr[3],u=ie);var l,f,d,p,h,m,g;l=t[0]^e[0],f=t[n?3:1]^e[1],d=t[2]^e[2],p=t[n?1:3]^e[3];for(var y=3,x=1;x<i;++x)h=o[l>>>24]^s[f>>>16&255]^a[d>>>8&255]^c[p&255]^e[++y],m=o[f>>>24]^s[d>>>16&255]^a[p>>>8&255]^c[l&255]^e[++y],g=o[d>>>24]^s[p>>>16&255]^a[l>>>8&255]^c[f&255]^e[++y],p=o[p>>>24]^s[l>>>16&255]^a[f>>>8&255]^c[d&255]^e[++y],l=h,f=m,d=g;r[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[d>>>8&255]<<8^u[p&255]^e[++y],r[n?3:1]=u[f>>>24]<<24^u[d>>>16&255]<<16^u[p>>>8&255]<<8^u[l&255]^e[++y],r[2]=u[d>>>24]<<24^u[p>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^e[++y],r[n?1:3]=u[p>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[d&255]^e[++y]}function Gi(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),r="AES-"+t,n;e.decrypt?n=dt.cipher.createDecipher(r,e.key):n=dt.cipher.createCipher(r,e.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof dt.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var wl=tt((tv,El)=>{var gt=ft();Ys();Qs();Lt();El.exports=gt.des=gt.des||{};gt.des.startEncrypting=function(e,t,r,n){var i=Yi({key:e,output:r,decrypt:!1,mode:n||(t===null?"ECB":"CBC")});return i.start(t),i};gt.des.createEncryptionCipher=function(e,t){return Yi({key:e,output:null,decrypt:!1,mode:t})};gt.des.startDecrypting=function(e,t,r,n){var i=Yi({key:e,output:r,decrypt:!0,mode:n||(t===null?"ECB":"CBC")});return i.start(t),i};gt.des.createDecryptionCipher=function(e,t){return Yi({key:e,output:null,decrypt:!0,mode:t})};gt.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(n,i){return vl(r._keys,n,i,!1)},decrypt:function(n,i){return vl(r._keys,n,i,!0)}}}),r._init=!1};gt.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=gt.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0&&t.length()!==24)throw new Error("Invalid Triple-DES key size: "+t.length()*8);this._keys=Sp(t),this._init=!0}};Oe("DES-ECB",gt.cipher.modes.ecb);Oe("DES-CBC",gt.cipher.modes.cbc);Oe("DES-CFB",gt.cipher.modes.cfb);Oe("DES-OFB",gt.cipher.modes.ofb);Oe("DES-CTR",gt.cipher.modes.ctr);Oe("3DES-ECB",gt.cipher.modes.ecb);Oe("3DES-CBC",gt.cipher.modes.cbc);Oe("3DES-CFB",gt.cipher.modes.cfb);Oe("3DES-OFB",gt.cipher.modes.ofb);Oe("3DES-CTR",gt.cipher.modes.ctr);function Oe(e,t){var r=function(){return new gt.des.Algorithm(e,t)};gt.cipher.registerAlgorithm(e,r)}var mp=[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],gp=[-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],yp=[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],xp=[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],bp=[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],vp=[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],Ep=[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],wp=[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 Sp(e){for(var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],d=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],h=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],m=e.length()>8?3:1,g=[],y=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],x=0,b,_=0;_<m;_++){var w=e.getInt32(),S=e.getInt32();b=(w>>>4^S)&252645135,S^=b,w^=b<<4,b=(S>>>-16^w)&65535,w^=b,S^=b<<-16,b=(w>>>2^S)&858993459,S^=b,w^=b<<2,b=(S>>>-16^w)&65535,w^=b,S^=b<<-16,b=(w>>>1^S)&1431655765,S^=b,w^=b<<1,b=(S>>>8^w)&16711935,w^=b,S^=b<<8,b=(w>>>1^S)&1431655765,S^=b,w^=b<<1,b=w<<8|S>>>20&240,w=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=b;for(var D=0;D<y.length;++D){y[D]?(w=w<<2|w>>>26,S=S<<2|S>>>26):(w=w<<1|w>>>27,S=S<<1|S>>>27),w&=-15,S&=-15;var P=t[w>>>28]|r[w>>>24&15]|n[w>>>20&15]|i[w>>>16&15]|o[w>>>12&15]|s[w>>>8&15]|a[w>>>4&15],$=c[S>>>28]|u[S>>>24&15]|l[S>>>20&15]|f[S>>>16&15]|d[S>>>12&15]|p[S>>>8&15]|h[S>>>4&15];b=($>>>16^P)&65535,g[x++]=P^b,g[x++]=$^b<<16}}return g}function vl(e,t,r,n){var i=e.length===32?3:9,o;i===3?o=n?[30,-2,-2]:[0,32,2]:o=n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,a=t[0],c=t[1];s=(a>>>4^c)&252645135,c^=s,a^=s<<4,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u<i;u+=3){for(var l=o[u+1],f=o[u+2],d=o[u];d!=l;d+=f){var p=c^e[d],h=(c>>>4|c<<28)^e[d+1];s=a,a=c,c=s^(gp[p>>>24&63]|xp[p>>>16&63]|vp[p>>>8&63]|wp[p&63]|mp[h>>>24&63]|yp[h>>>16&63]|bp[h>>>8&63]|Ep[h&63])}s=a,a=c,c=s}a=a>>>1|a<<31,c=c>>>1|c<<31,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(a>>>4^c)&252645135,c^=s,a^=s<<4,r[0]=a,r[1]=c}function Yi(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),r="DES-"+t,n;e.decrypt?n=gt.cipher.createDecipher(r,e.key):n=gt.cipher.createCipher(r,e.key);var i=n.start;return n.start=function(o,s){var a=null;s instanceof gt.util.ByteBuffer&&(a=s,s={}),s=s||{},s.output=a,s.iv=o,i.call(n,s)},n}});var Or=tt((ev,Sl)=>{var Wi=ft();Sl.exports=Wi.md=Wi.md||{};Wi.md.algorithms=Wi.md.algorithms||{}});var Il=tt((rv,Al)=>{var We=ft();Or();Lt();var Ap=Al.exports=We.hmac=We.hmac||{};Ap.create=function(){var e=null,t=null,r=null,n=null,i={};return i.start=function(o,s){if(o!==null)if(typeof o=="string")if(o=o.toLowerCase(),o in We.md.algorithms)t=We.md.algorithms[o].create();else throw new Error('Unknown hash algorithm "'+o+'"');else t=o;if(s===null)s=e;else{if(typeof s=="string")s=We.util.createBuffer(s);else if(We.util.isArray(s)){var a=s;s=We.util.createBuffer();for(var c=0;c<a.length;++c)s.putByte(a[c])}var u=s.length();u>t.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=We.util.createBuffer(),n=We.util.createBuffer(),u=s.length();for(var c=0;c<u;++c){var a=s.at(c);r.putByte(54^a),n.putByte(92^a)}if(u<t.blockLength)for(var a=t.blockLength-u,c=0;c<a;++c)r.putByte(54),n.putByte(92);e=s,r=r.bytes(),n=n.bytes()}t.start(),t.update(r)},i.update=function(o){t.update(o)},i.getMac=function(){var o=t.digest().bytes();return t.start(),t.update(n),t.update(o),t.digest()},i.digest=i.getMac,i}});var Qi=tt(()=>{});var Cl=tt((ov,_l)=>{var oe=ft();Il();Or();Lt();var Ip=oe.pkcs5=oe.pkcs5||{},Qe;oe.util.isNodejs&&!oe.options.usePureJavaScript&&(Qe=Qi());_l.exports=oe.pbkdf2=Ip.pbkdf2=function(e,t,r,n,i,o){if(typeof i=="function"&&(o=i,i=null),oe.util.isNodejs&&!oe.options.usePureJavaScript&&Qe.pbkdf2&&(i===null||typeof i!="object")&&(Qe.pbkdf2Sync.length>4||!i||i==="sha1"))return typeof i!="string"&&(i="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?Qe.pbkdf2Sync.length===4?Qe.pbkdf2(e,t,r,n,function(b,_){if(b)return o(b);o(null,_.toString("binary"))}):Qe.pbkdf2(e,t,r,n,i,function(b,_){if(b)return o(b);o(null,_.toString("binary"))}):Qe.pbkdf2Sync.length===4?Qe.pbkdf2Sync(e,t,r,n).toString("binary"):Qe.pbkdf2Sync(e,t,r,n,i).toString("binary");if((typeof i>"u"||i===null)&&(i="sha1"),typeof i=="string"){if(!(i in oe.md.algorithms))throw new Error("Unknown hash algorithm: "+i);i=oe.md[i].create()}var s=i.digestLength;if(n>4294967295*s){var a=new Error("Derived key is too long.");if(o)return o(a);throw a}var c=Math.ceil(n/s),u=n-(c-1)*s,l=oe.hmac.create();l.start(i,e);var f="",d,p,h;if(!o){for(var m=1;m<=c;++m){l.start(null,null),l.update(t),l.update(oe.util.int32ToBytes(m)),d=h=l.digest().getBytes();for(var g=2;g<=r;++g)l.start(null,null),l.update(h),p=l.digest().getBytes(),d=oe.util.xorBytes(d,p,s),h=p;f+=m<c?d:d.substr(0,u)}return f}var m=1,g;function y(){if(m>c)return o(null,f);l.start(null,null),l.update(t),l.update(oe.util.int32ToBytes(m)),d=h=l.digest().getBytes(),g=2,x()}function x(){if(g<=r)return l.start(null,null),l.update(h),p=l.digest().getBytes(),d=oe.util.xorBytes(d,p,s),h=p,++g,oe.util.setImmediate(x);f+=m<c?d:d.substr(0,u),++m,y()}y()}});var Bl=tt((sv,Tl)=>{var Zi=ft();Lt();var Rl=Tl.exports=Zi.pem=Zi.pem||{};Rl.encode=function(e,t){t=t||{};var r="-----BEGIN "+e.type+`-----\r
|
|
9
|
+
`,n;if(e.procType&&(n={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},r+=Xi(n)),e.contentDomain&&(n={name:"Content-Domain",values:[e.contentDomain]},r+=Xi(n)),e.dekInfo&&(n={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&n.values.push(e.dekInfo.parameters),r+=Xi(n)),e.headers)for(var i=0;i<e.headers.length;++i)r+=Xi(e.headers[i]);return e.procType&&(r+=`\r
|
|
10
|
+
`),r+=Zi.util.encode64(e.body,t.maxline||64)+`\r
|
|
11
|
+
`,r+="-----END "+e.type+`-----\r
|
|
12
|
+
`,r};Rl.decode=function(e){for(var t=[],r=/\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/,o;o=r.exec(e),!!o;){var s=o[1];s==="NEW CERTIFICATE REQUEST"&&(s="CERTIFICATE REQUEST");var a={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Zi.util.decode64(o[3])};if(t.push(a),!!o[2]){for(var c=o[2].split(i),u=0;o&&u<c.length;){for(var l=c[u].replace(/\s+$/,""),f=u+1;f<c.length;++f){var d=c[f];if(!/\s/.test(d[0]))break;l+=d,u=f}if(o=l.match(n),o){for(var p={name:o[1],values:[]},h=o[2].split(","),m=0;m<h.length;++m)p.values.push(_p(h[m]));if(a.procType)if(!a.contentDomain&&p.name==="Content-Domain")a.contentDomain=h[0]||"";else if(!a.dekInfo&&p.name==="DEK-Info"){if(p.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');a.dekInfo={algorithm:h[0],parameters:h[1]||null}}else a.headers.push(p);else{if(p.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(p.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');a.procType={version:h[0],type:h[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(t.length===0)throw new Error("Invalid PEM formatted message.");return t};function Xi(e){for(var t=e.name+": ",r=[],n=function(c,u){return" "+u},i=0;i<e.values.length;++i)r.push(e.values[i].replace(/^(\S+\r\n)/,n));t+=r.join(",")+`\r
|
|
13
|
+
`;for(var o=0,s=-1,i=0;i<t.length;++i,++o)if(o>65&&s!==-1){var a=t[s];a===","?(++s,t=t.substr(0,s)+`\r
|
|
14
|
+
`+t.substr(s)):t=t.substr(0,s)+`\r
|
|
15
|
+
`+a+t.substr(s+1),o=i-s-1,s=-1,++i}else(t[i]===" "||t[i]===" "||t[i]===",")&&(s=i);return t}function _p(e){return e.replace(/^\s+/,"")}});var kl=tt((av,Ol)=>{var ke=ft();Or();Lt();var Dl=Ol.exports=ke.sha256=ke.sha256||{};ke.md.sha256=ke.md.algorithms.sha256=Dl;Dl.create=function(){Pl||Cp();var e=null,t=ke.util.createBuffer(),r=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o<i;++o)n.fullMessageLength.push(0);return t=ke.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},n},n.start(),n.update=function(i,o){o==="utf8"&&(i=ke.util.encodeUtf8(i));var s=i.length;n.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(i),Ll(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var i=ke.util.createBuffer();i.putBytes(t.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(ta.substr(0,n.blockLength-s));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 f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};Ll(f,r,i);var d=ke.util.createBuffer();return d.putInt32(f.h0),d.putInt32(f.h1),d.putInt32(f.h2),d.putInt32(f.h3),d.putInt32(f.h4),d.putInt32(f.h5),d.putInt32(f.h6),d.putInt32(f.h7),d},n};var ta=null,Pl=!1,Nl=null;function Cp(){ta="\x80",ta+=ke.util.fillString("\0",64),Nl=[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],Pl=!0}function Ll(e,t,r){for(var n,i,o,s,a,c,u,l,f,d,p,h,m,g,y,x=r.length();x>=64;){for(u=0;u<16;++u)t[u]=r.getInt32();for(;u<64;++u)n=t[u-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=t[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[u]=n+t[u-7]+i+t[u-16]|0;for(l=e.h0,f=e.h1,d=e.h2,p=e.h3,h=e.h4,m=e.h5,g=e.h6,y=e.h7,u=0;u<64;++u)s=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),a=g^h&(m^g),o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|d&(l^f),n=y+s+a+Nl[u]+t[u],i=o+c,y=g,g=m,m=h,h=p+n>>>0,p=d,d=f,f=l,l=n+i>>>0;e.h0=e.h0+l|0,e.h1=e.h1+f|0,e.h2=e.h2+d|0,e.h3=e.h3+p|0,e.h4=e.h4+h|0,e.h5=e.h5+m|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,x-=64}}});var Ul=tt((cv,Ml)=>{var Me=ft();Lt();var Ji=null;Me.util.isNodejs&&!Me.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Ji=Qi());var Rp=Ml.exports=Me.prng=Me.prng||{};Rp.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=new Array(32),i=0;i<32;++i)n[i]=r.create();t.pools=n,t.pool=0,t.generate=function(u,l){if(!l)return t.generateSync(u);var f=t.plugin.cipher,d=t.plugin.increment,p=t.plugin.formatKey,h=t.plugin.formatSeed,m=Me.util.createBuffer();t.key=null,g();function g(y){if(y)return l(y);if(m.length()>=u)return l(null,m.getBytes(u));if(t.generated>1048575&&(t.key=null),t.key===null)return Me.util.nextTick(function(){o(g)});var x=f(t.key,t.seed);t.generated+=x.length,m.putBytes(x),t.key=p(f(t.key,d(t.seed))),t.seed=h(f(t.key,t.seed)),Me.util.setImmediate(g)}},t.generateSync=function(u){var l=t.plugin.cipher,f=t.plugin.increment,d=t.plugin.formatKey,p=t.plugin.formatSeed;t.key=null;for(var h=Me.util.createBuffer();h.length()<u;){t.generated>1048575&&(t.key=null),t.key===null&&s();var m=l(t.key,t.seed);t.generated+=m.length,h.putBytes(m),t.key=d(l(t.key,f(t.seed))),t.seed=p(l(t.key,t.seed))}return h.getBytes(u)};function o(u){if(t.pools[0].messageLength>=32)return a(),u();var l=32-t.pools[0].messageLength<<5;t.seedFile(l,function(f,d){if(f)return u(f);t.collect(d),a(),u()})}function s(){if(t.pools[0].messageLength>=32)return a();var u=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(u)),a()}function a(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var u=t.plugin.md.create();u.update(t.keyBytes);for(var l=1,f=0;f<32;++f)t.reseeds%l===0&&(u.update(t.pools[f].digest().getBytes()),t.pools[f].start()),l=l<<1;t.keyBytes=u.digest().getBytes(),u.start(),u.update(t.keyBytes);var d=u.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(d),t.generated=0}function c(u){var l=null,f=Me.util.globalScope,d=f.crypto||f.msCrypto;d&&d.getRandomValues&&(l=function(w){return d.getRandomValues(w)});var p=Me.util.createBuffer();if(l)for(;p.length()<u;){var h=Math.max(1,Math.min(u-p.length(),65536)/4),m=new Uint32Array(Math.floor(h));try{l(m);for(var g=0;g<m.length;++g)p.putInt32(m[g])}catch(w){if(!(typeof QuotaExceededError<"u"&&w instanceof QuotaExceededError))throw w}}if(p.length()<u)for(var y,x,b,_=Math.floor(Math.random()*65536);p.length()<u;){x=16807*(_&65535),y=16807*(_>>16),x+=(y&32767)<<16,x+=y>>15,x=(x&2147483647)+(x>>31),_=x&4294967295;for(var g=0;g<3;++g)b=_>>>(g<<3),b^=Math.floor(Math.random()*256),p.putByte(b&255)}return p.getBytes(u)}return Ji?(t.seedFile=function(u,l){Ji.randomBytes(u,function(f,d){if(f)return l(f);l(null,d.toString())})},t.seedFileSync=function(u){return Ji.randomBytes(u).toString()}):(t.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},t.seedFileSync=c),t.collect=function(u){for(var l=u.length,f=0;f<l;++f)t.pools[t.pool].update(u.substr(f,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(u,l){for(var f="",d=0;d<l;d+=8)f+=String.fromCharCode(u>>d&255);t.collect(f)},t.registerWorker=function(u){if(u===self)t.seedFile=function(f,d){function p(h){var m=h.data;m.forge&&m.forge.prng&&(self.removeEventListener("message",p),d(m.forge.prng.err,m.forge.prng.bytes))}self.addEventListener("message",p),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var d=f.data;d.forge&&d.forge.prng&&t.seedFile(d.forge.prng.needed,function(p,h){u.postMessage({forge:{prng:{err:p,bytes:h}}})})};u.addEventListener("message",l)}},t}});var oi=tt((uv,ea)=>{var Vt=ft();js();kl();Ul();Lt();(function(){if(Vt.random&&Vt.random.getBytes){ea.exports=Vt.random;return}(function(e){var t={},r=new Array(4),n=Vt.util.createBuffer();t.formatKey=function(f){var d=Vt.util.createBuffer(f);return f=new Array(4),f[0]=d.getInt32(),f[1]=d.getInt32(),f[2]=d.getInt32(),f[3]=d.getInt32(),Vt.aes._expandKey(f,!1)},t.formatSeed=function(f){var d=Vt.util.createBuffer(f);return f=new Array(4),f[0]=d.getInt32(),f[1]=d.getInt32(),f[2]=d.getInt32(),f[3]=d.getInt32(),f},t.cipher=function(f,d){return Vt.aes._updateBlock(f,d,r,!1),n.putInt32(r[0]),n.putInt32(r[1]),n.putInt32(r[2]),n.putInt32(r[3]),n.getBytes()},t.increment=function(f){return++f[3],f},t.md=Vt.md.sha256;function i(){var f=Vt.prng.create(t);return f.getBytes=function(d,p){return f.generate(d,p)},f.getBytesSync=function(d){return f.generate(d)},f}var o=i(),s=null,a=Vt.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues&&(s=function(f){return c.getRandomValues(f)}),Vt.options.usePureJavaScript||!Vt.util.isNodejs&&!s){if(typeof window>"u"||window.document,o.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{typeof navigator[l]=="string"&&(u+=navigator[l])}catch{}o.collect(u),u=null}e&&(e().mousemove(function(f){o.collectInt(f.clientX,16),o.collectInt(f.clientY,16)}),e().keypress(function(f){o.collectInt(f.charCode,8)}))}if(!Vt.random)Vt.random=o;else for(var l in o)Vt.random[l]=o[l];Vt.random.createInstance=i,ea.exports=Vt.random})(typeof jQuery<"u"?jQuery:null)})()});var ql=tt((lv,Vl)=>{var ae=ft();Lt();var ra=[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],Fl=[1,2,3,5],Tp=function(e,t){return e<<t&65535|(e&65535)>>16-t},Bp=function(e,t){return(e&65535)>>t|e<<16-t&65535};Vl.exports=ae.rc2=ae.rc2||{};ae.rc2.expandKey=function(e,t){typeof e=="string"&&(e=ae.util.createBuffer(e)),t=t||128;var r=e,n=e.length(),i=t,o=Math.ceil(i/8),s=255>>(i&7),a;for(a=n;a<128;a++)r.putByte(ra[r.at(a-1)+r.at(a-n)&255]);for(r.setAt(128-o,ra[r.at(128-o)&s]),a=127-o;a>=0;a--)r.setAt(a,ra[r.at(a+1)^r.at(a+o)]);return r};var Kl=function(e,t,r){var n=!1,i=null,o=null,s=null,a,c,u,l,f=[];for(e=ae.rc2.expandKey(e,t),u=0;u<64;u++)f.push(e.getInt16Le());r?(a=function(h){for(u=0;u<4;u++)h[u]+=f[l]+(h[(u+3)%4]&h[(u+2)%4])+(~h[(u+3)%4]&h[(u+1)%4]),h[u]=Tp(h[u],Fl[u]),l++},c=function(h){for(u=0;u<4;u++)h[u]+=f[h[(u+3)%4]&63]}):(a=function(h){for(u=3;u>=0;u--)h[u]=Bp(h[u],Fl[u]),h[u]-=f[l]+(h[(u+3)%4]&h[(u+2)%4])+(~h[(u+3)%4]&h[(u+1)%4]),l--},c=function(h){for(u=3;u>=0;u--)h[u]-=f[h[(u+3)%4]&63]});var d=function(h){var m=[];for(u=0;u<4;u++){var g=i.getInt16Le();s!==null&&(r?g^=s.getInt16Le():s.putInt16Le(g)),m.push(g&65535)}l=r?0:63;for(var y=0;y<h.length;y++)for(var x=0;x<h[y][0];x++)h[y][1](m);for(u=0;u<4;u++)s!==null&&(r?s.putInt16Le(m[u]):m[u]^=s.getInt16Le()),o.putInt16Le(m[u])},p=null;return p={start:function(h,m){h&&typeof h=="string"&&(h=ae.util.createBuffer(h)),n=!1,i=ae.util.createBuffer(),o=m||new ae.util.createBuffer,s=h,p.output=o},update:function(h){for(n||i.putBuffer(h);i.length()>=8;)d([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(h){var m=!0;if(r)if(h)m=h(8,i,!r);else{var g=i.length()===8?8:8-i.length();i.fillWithByte(g,g)}if(m&&(n=!0,p.update()),!r&&(m=i.length()===0,m))if(h)m=h(8,o,!r);else{var y=o.length(),x=o.at(y-1);x>y?m=!1:o.truncate(x)}return m}},p};ae.rc2.startEncrypting=function(e,t,r){var n=ae.rc2.createEncryptionCipher(e,128);return n.start(t,r),n};ae.rc2.createEncryptionCipher=function(e,t){return Kl(e,t,!0)};ae.rc2.startDecrypting=function(e,t,r){var n=ae.rc2.createDecryptionCipher(e,128);return n.start(t,r),n};ae.rc2.createDecryptionCipher=function(e,t){return Kl(e,t,!1)}});var eo=tt((fv,Xl)=>{var na=ft();Xl.exports=na.jsbn=na.jsbn||{};var Xe,Lp=0xdeadbeefcafe,zl=(Lp&16777215)==15715070;function R(e,t,r){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,r):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}na.jsbn.BigInteger=R;function nt(){return new R(null)}function Dp(e,t,r,n,i,o){for(;--o>=0;){var s=t*this.data[e++]+r.data[n]+i;i=Math.floor(s/67108864),r.data[n++]=s&67108863}return i}function Pp(e,t,r,n,i,o){for(var s=t&32767,a=t>>15;--o>=0;){var c=this.data[e]&32767,u=this.data[e++]>>15,l=a*c+u*s;c=s*c+((l&32767)<<15)+r.data[n]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),r.data[n++]=c&1073741823}return i}function $l(e,t,r,n,i,o){for(var s=t&16383,a=t>>14;--o>=0;){var c=this.data[e]&16383,u=this.data[e++]>>14,l=a*c+u*s;c=s*c+((l&16383)<<14)+r.data[n]+i,i=(c>>28)+(l>>14)+a*u,r.data[n++]=c&268435455}return i}typeof navigator>"u"?(R.prototype.am=$l,Xe=28):zl&&navigator.appName=="Microsoft Internet Explorer"?(R.prototype.am=Pp,Xe=30):zl&&navigator.appName!="Netscape"?(R.prototype.am=Dp,Xe=26):(R.prototype.am=$l,Xe=28);R.prototype.DB=Xe;R.prototype.DM=(1<<Xe)-1;R.prototype.DV=1<<Xe;var ia=52;R.prototype.FV=Math.pow(2,ia);R.prototype.F1=ia-Xe;R.prototype.F2=2*Xe-ia;var Np="0123456789abcdefghijklmnopqrstuvwxyz",ji=new Array,gn,ye;gn=48;for(ye=0;ye<=9;++ye)ji[gn++]=ye;gn=97;for(ye=10;ye<36;++ye)ji[gn++]=ye;gn=65;for(ye=10;ye<36;++ye)ji[gn++]=ye;function Hl(e){return Np.charAt(e)}function Gl(e,t){var r=ji[e.charCodeAt(t)];return r??-1}function Op(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function kp(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function fr(e){var t=nt();return t.fromInt(e),t}function Mp(e,t){var r;if(t==16)r=4;else if(t==8)r=3;else if(t==256)r=8;else if(t==2)r=1;else if(t==32)r=5;else if(t==4)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=r==8?e[n]&255:Gl(e,n);if(s<0){e.charAt(n)=="-"&&(i=!0);continue}i=!1,o==0?this.data[this.t++]=s:o+r>this.DB?(this.data[this.t-1]|=(s&(1<<this.DB-o)-1)<<o,this.data[this.t++]=s>>this.DB-o):this.data[this.t-1]|=s<<o,o+=r,o>=this.DB&&(o-=this.DB)}r==8&&e[0]&128&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),i&&R.ZERO.subTo(this,this)}function Up(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t}function Fp(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var r=(1<<t)-1,n,i=!1,o="",s=this.t,a=this.DB-s*this.DB%t;if(s-- >0)for(a<this.DB&&(n=this.data[s]>>a)>0&&(i=!0,o=Hl(n));s>=0;)a<t?(n=(this.data[s]&(1<<a)-1)<<t-a,n|=this.data[--s]>>(a+=this.DB-t)):(n=this.data[s]>>(a-=t)&r,a<=0&&(a+=this.DB,--s)),n>0&&(i=!0),i&&(o+=Hl(n));return i?o:"0"}function Kp(){var e=nt();return R.ZERO.subTo(this,e),e}function Vp(){return this.s<0?this.negate():this}function qp(e){var t=this.s-e.s;if(t!=0)return t;var r=this.t;if(t=r-e.t,t!=0)return this.s<0?-t:t;for(;--r>=0;)if((t=this.data[r]-e.data[r])!=0)return t;return 0}function to(e){var t=1,r;return(r=e>>>16)!=0&&(e=r,t+=16),(r=e>>8)!=0&&(e=r,t+=8),(r=e>>4)!=0&&(e=r,t+=4),(r=e>>2)!=0&&(e=r,t+=2),(r=e>>1)!=0&&(e=r,t+=1),t}function zp(){return this.t<=0?0:this.DB*(this.t-1)+to(this.data[this.t-1]^this.s&this.DM)}function $p(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function Hp(e,t){for(var r=e;r<this.t;++r)t.data[r-e]=this.data[r];t.t=Math.max(this.t-e,0),t.s=this.s}function Gp(e,t){var r=e%this.DB,n=this.DB-r,i=(1<<n)-1,o=Math.floor(e/this.DB),s=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)t.data[a+o+1]=this.data[a]>>n|s,s=(this.data[a]&i)<<r;for(a=o-1;a>=0;--a)t.data[a]=0;t.data[o]=s,t.t=this.t+o+1,t.s=this.s,t.clamp()}function Yp(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,i=this.DB-n,o=(1<<n)-1;t.data[0]=this.data[r]>>n;for(var s=r+1;s<this.t;++s)t.data[s-r-1]|=(this.data[s]&o)<<i,t.data[s-r]=this.data[s]>>n;n>0&&(t.data[this.t-r-1]|=(this.s&o)<<i),t.t=this.t-r,t.clamp()}function Wp(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this.data[r]-e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()}function Qp(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i<n.t;++i)t.data[i+r.t]=r.am(0,n.data[i],t,i,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&R.ZERO.subTo(t,t)}function Xp(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e.data[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t.data[r],e,2*r,0,1);(e.data[r+t.t]+=t.am(r+1,2*t.data[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function Zp(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){t?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=nt());var o=nt(),s=this.s,a=e.s,c=this.DB-to(n.data[n.t-1]);c>0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var u=o.t,l=o.data[u-1];if(l!=0){var f=l*(1<<this.F1)+(u>1?o.data[u-2]>>this.F2:0),d=this.FV/f,p=(1<<this.F1)/f,h=1<<this.F2,m=r.t,g=m-u,y=t??nt();for(o.dlShiftTo(g,y),r.compareTo(y)>=0&&(r.data[r.t++]=1,r.subTo(y,r)),R.ONE.dlShiftTo(u,y),y.subTo(o,o);o.t<u;)o.data[o.t++]=0;for(;--g>=0;){var x=r.data[--m]==l?this.DM:Math.floor(r.data[m]*d+(r.data[m-1]+h)*p);if((r.data[m]+=o.am(0,x,r,g,0,u))<x)for(o.dlShiftTo(g,y),r.subTo(y,r);r.data[m]<--x;)r.subTo(y,r)}t!=null&&(r.drShiftTo(u,t),s!=a&&R.ZERO.subTo(t,t)),r.t=u,r.clamp(),c>0&&r.rShiftTo(c,r),s<0&&R.ZERO.subTo(r,r)}}}function Jp(e){var t=nt();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(R.ZERO)>0&&e.subTo(t,t),t}function kr(e){this.m=e}function jp(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function tm(e){return e}function em(e){e.divRemTo(this.m,null,e)}function rm(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function nm(e,t){e.squareTo(t),this.reduce(t)}kr.prototype.convert=jp;kr.prototype.revert=tm;kr.prototype.reduce=em;kr.prototype.mulTo=rm;kr.prototype.sqrTo=nm;function im(){if(this.t<1)return 0;var e=this.data[0];if(!(e&1))return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function Mr(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function om(e){var t=nt();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(R.ZERO)>0&&this.m.subTo(t,t),t}function sm(e){var t=nt();return e.copyTo(t),this.reduce(t),t}function am(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=e.data[t]&32767,n=r*this.mpl+((r*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function cm(e,t){e.squareTo(t),this.reduce(t)}function um(e,t,r){e.multiplyTo(t,r),this.reduce(r)}Mr.prototype.convert=om;Mr.prototype.revert=sm;Mr.prototype.reduce=am;Mr.prototype.mulTo=um;Mr.prototype.sqrTo=cm;function lm(){return(this.t>0?this.data[0]&1:this.s)==0}function fm(e,t){if(e>4294967295||e<1)return R.ONE;var r=nt(),n=nt(),i=t.convert(this),o=to(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<<o)>0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)}function hm(e,t){var r;return e<256||t.isEven()?r=new kr(t):r=new Mr(t),this.exp(e,r)}R.prototype.copyTo=Op;R.prototype.fromInt=kp;R.prototype.fromString=Mp;R.prototype.clamp=Up;R.prototype.dlShiftTo=$p;R.prototype.drShiftTo=Hp;R.prototype.lShiftTo=Gp;R.prototype.rShiftTo=Yp;R.prototype.subTo=Wp;R.prototype.multiplyTo=Qp;R.prototype.squareTo=Xp;R.prototype.divRemTo=Zp;R.prototype.invDigit=im;R.prototype.isEven=lm;R.prototype.exp=fm;R.prototype.toString=Fp;R.prototype.negate=Kp;R.prototype.abs=Vp;R.prototype.compareTo=qp;R.prototype.bitLength=zp;R.prototype.mod=Jp;R.prototype.modPowInt=hm;R.ZERO=fr(0);R.ONE=fr(1);function dm(){var e=nt();return this.copyTo(e),e}function pm(){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 mm(){return this.t==0?this.s:this.data[0]<<24>>24}function gm(){return this.t==0?this.s:this.data[0]<<16>>16}function ym(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function xm(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function bm(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=fr(r),i=nt(),o=nt(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s}function vm(e,t){this.fromInt(0),t==null&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a<e.length;++a){var c=Gl(e,a);if(c<0){e.charAt(a)=="-"&&this.signum()==0&&(i=!0);continue}s=t*s+c,++o>=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0)}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&R.ZERO.subTo(this,this)}function Em(e,t,r){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(R.ONE.shiftLeft(e-1),oa,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(R.ONE.shiftLeft(e-1),this);else{var n=new Array,i=e&7;n.length=(e>>3)+1,t.nextBytes(n),i>0?n[0]&=(1<<i)-1:n[0]=0,this.fromString(n,256)}}function wm(){var e=this.t,t=new Array;t[0]=this.s;var r=this.DB-e*this.DB%8,n,i=0;if(e-- >0)for(r<this.DB&&(n=this.data[e]>>r)!=(this.s&this.DM)>>r&&(t[i++]=n|this.s<<this.DB-r);e>=0;)r<8?(n=(this.data[e]&(1<<r)-1)<<8-r,n|=this.data[--e]>>(r+=this.DB-8)):(n=this.data[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),n&128&&(n|=-256),i==0&&(this.s&128)!=(n&128)&&++i,(i>0||n!=this.s)&&(t[i++]=n);return t}function Sm(e){return this.compareTo(e)==0}function Am(e){return this.compareTo(e)<0?this:e}function Im(e){return this.compareTo(e)>0?this:e}function _m(e,t,r){var n,i,o=Math.min(e.t,this.t);for(n=0;n<o;++n)r.data[n]=t(this.data[n],e.data[n]);if(e.t<this.t){for(i=e.s&this.DM,n=o;n<this.t;++n)r.data[n]=t(this.data[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=o;n<e.t;++n)r.data[n]=t(i,e.data[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()}function Cm(e,t){return e&t}function Rm(e){var t=nt();return this.bitwiseTo(e,Cm,t),t}function oa(e,t){return e|t}function Tm(e){var t=nt();return this.bitwiseTo(e,oa,t),t}function Yl(e,t){return e^t}function Bm(e){var t=nt();return this.bitwiseTo(e,Yl,t),t}function Wl(e,t){return e&~t}function Lm(e){var t=nt();return this.bitwiseTo(e,Wl,t),t}function Dm(){for(var e=nt(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function Pm(e){var t=nt();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t}function Nm(e){var t=nt();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t}function Om(e){if(e==0)return-1;var t=0;return e&65535||(e>>=16,t+=16),e&255||(e>>=8,t+=8),e&15||(e>>=4,t+=4),e&3||(e>>=2,t+=2),e&1||++t,t}function km(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+Om(this.data[e]);return this.s<0?this.t*this.DB:-1}function Mm(e){for(var t=0;e!=0;)e&=e-1,++t;return t}function Um(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=Mm(this.data[r]^t);return e}function Fm(e){var t=Math.floor(e/this.DB);return t>=this.t?this.s!=0:(this.data[t]&1<<e%this.DB)!=0}function Km(e,t){var r=R.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r}function Vm(e){return this.changeBit(e,oa)}function qm(e){return this.changeBit(e,Wl)}function zm(e){return this.changeBit(e,Yl)}function $m(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this.data[r]+e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()}function Hm(e){var t=nt();return this.addTo(e,t),t}function Gm(e){var t=nt();return this.subTo(e,t),t}function Ym(e){var t=nt();return this.multiplyTo(e,t),t}function Wm(e){var t=nt();return this.divRemTo(e,t,null),t}function Qm(e){var t=nt();return this.divRemTo(e,null,t),t}function Xm(e){var t=nt(),r=nt();return this.divRemTo(e,t,r),new Array(t,r)}function Zm(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function Jm(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function si(){}function Ql(e){return e}function jm(e,t,r){e.multiplyTo(t,r)}function tg(e,t){e.squareTo(t)}si.prototype.convert=Ql;si.prototype.revert=Ql;si.prototype.mulTo=jm;si.prototype.sqrTo=tg;function eg(e){return this.exp(e,new si)}function rg(e,t,r){var n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var i;for(i=r.t-this.t;n<i;++n)r.data[n+this.t]=this.am(0,e.data[n],r,n,0,this.t);for(i=Math.min(e.t,t);n<i;++n)this.am(0,e.data[n],r,n,0,t-n);r.clamp()}function ng(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r.data[this.t+n-t]=this.am(t-n,e.data[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)}function yn(e){this.r2=nt(),this.q3=nt(),R.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function ig(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nt();return e.copyTo(t),this.reduce(t),t}function og(e){return e}function sg(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function ag(e,t){e.squareTo(t),this.reduce(t)}function cg(e,t,r){e.multiplyTo(t,r),this.reduce(r)}yn.prototype.convert=ig;yn.prototype.revert=og;yn.prototype.reduce=sg;yn.prototype.mulTo=cg;yn.prototype.sqrTo=ag;function ug(e,t){var r=e.bitLength(),n,i=fr(1),o;if(r<=0)return i;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6,r<8?o=new kr(t):t.isEven()?o=new yn(t):o=new Mr(t);var s=new Array,a=3,c=n-1,u=(1<<n)-1;if(s[1]=o.convert(this),n>1){var l=nt();for(o.sqrTo(s[1],l);a<=u;)s[a]=nt(),o.mulTo(l,s[a-2],s[a]),a+=2}var f=e.t-1,d,p=!0,h=nt(),m;for(r=to(e.data[f])-1;f>=0;){for(r>=c?d=e.data[f]>>r-c&u:(d=(e.data[f]&(1<<r+1)-1)<<c-r,f>0&&(d|=e.data[f-1]>>this.DB+r-c)),a=n;!(d&1);)d>>=1,--a;if((r-=a)<0&&(r+=this.DB,--f),p)s[d].copyTo(i),p=!1;else{for(;a>1;)o.sqrTo(i,h),o.sqrTo(h,i),a-=2;a>0?o.sqrTo(i,h):(m=i,i=h,h=m),o.mulTo(h,s[d],i)}for(;f>=0&&!(e.data[f]&1<<r);)o.sqrTo(i,h),m=i,i=h,h=m,--r<0&&(r=this.DB-1,--f)}return o.revert(i)}function lg(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i<o&&(o=i),o>0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r}function fg(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(t==0)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r}function hg(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return R.ZERO;for(var r=e.clone(),n=this.clone(),i=fr(1),o=fr(0),s=fr(0),a=fr(1);r.signum()!=0;){for(;r.isEven();)r.rShiftTo(1,r),t?((!i.isEven()||!o.isEven())&&(i.addTo(this,i),o.subTo(e,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),t?((!s.isEven()||!a.isEven())&&(s.addTo(this,s),a.subTo(e,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}if(n.compareTo(R.ONE)!=0)return R.ZERO;if(a.compareTo(e)>=0)return a.subtract(e);if(a.signum()<0)a.addTo(e,a);else return a;return a.signum()<0?a.add(e):a}var Ie=[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],dg=(1<<26)/Ie[Ie.length-1];function pg(e){var t,r=this.abs();if(r.t==1&&r.data[0]<=Ie[Ie.length-1]){for(t=0;t<Ie.length;++t)if(r.data[0]==Ie[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<Ie.length;){for(var n=Ie[t],i=t+1;i<Ie.length&&n<dg;)n*=Ie[i++];for(n=r.modInt(n);t<i;)if(n%Ie[t++]==0)return!1}return r.millerRabin(e)}function mg(e){var t=this.subtract(R.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n=t.shiftRight(r),i=gg(),o,s=0;s<e;++s){do o=new R(this.bitLength(),i);while(o.compareTo(R.ONE)<=0||o.compareTo(t)>=0);var a=o.modPow(n,this);if(a.compareTo(R.ONE)!=0&&a.compareTo(t)!=0){for(var c=1;c++<r&&a.compareTo(t)!=0;)if(a=a.modPowInt(2,this),a.compareTo(R.ONE)==0)return!1;if(a.compareTo(t)!=0)return!1}}return!0}function gg(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}R.prototype.chunkSize=ym;R.prototype.toRadix=bm;R.prototype.fromRadix=vm;R.prototype.fromNumber=Em;R.prototype.bitwiseTo=_m;R.prototype.changeBit=Km;R.prototype.addTo=$m;R.prototype.dMultiply=Zm;R.prototype.dAddOffset=Jm;R.prototype.multiplyLowerTo=rg;R.prototype.multiplyUpperTo=ng;R.prototype.modInt=fg;R.prototype.millerRabin=mg;R.prototype.clone=dm;R.prototype.intValue=pm;R.prototype.byteValue=mm;R.prototype.shortValue=gm;R.prototype.signum=xm;R.prototype.toByteArray=wm;R.prototype.equals=Sm;R.prototype.min=Am;R.prototype.max=Im;R.prototype.and=Rm;R.prototype.or=Tm;R.prototype.xor=Bm;R.prototype.andNot=Lm;R.prototype.not=Dm;R.prototype.shiftLeft=Pm;R.prototype.shiftRight=Nm;R.prototype.getLowestSetBit=km;R.prototype.bitCount=Um;R.prototype.testBit=Fm;R.prototype.setBit=Vm;R.prototype.clearBit=qm;R.prototype.flipBit=zm;R.prototype.add=Hm;R.prototype.subtract=Gm;R.prototype.multiply=Ym;R.prototype.divide=Wm;R.prototype.remainder=Qm;R.prototype.divideAndRemainder=Xm;R.prototype.modPow=ug;R.prototype.modInverse=hg;R.prototype.pow=eg;R.prototype.gcd=lg;R.prototype.isProbablePrime=pg});var ef=tt((hv,tf)=>{var Ue=ft();Or();Lt();var Jl=tf.exports=Ue.sha1=Ue.sha1||{};Ue.md.sha1=Ue.md.algorithms.sha1=Jl;Jl.create=function(){jl||yg();var e=null,t=Ue.util.createBuffer(),r=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return n.start=function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,o=0;o<i;++o)n.fullMessageLength.push(0);return t=Ue.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},n},n.start(),n.update=function(i,o){o==="utf8"&&(i=Ue.util.encodeUtf8(i));var s=i.length;n.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=n.fullMessageLength.length-1;a>=0;--a)n.fullMessageLength[a]+=s[1],s[1]=s[0]+(n.fullMessageLength[a]/4294967296>>>0),n.fullMessageLength[a]=n.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(i),Zl(e,r,t),(t.read>2048||t.length()===0)&&t.compact(),n},n.digest=function(){var i=Ue.util.createBuffer();i.putBytes(t.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize,s=o&n.blockLength-1;i.putBytes(sa.substr(0,n.blockLength-s));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 f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Zl(f,r,i);var d=Ue.util.createBuffer();return d.putInt32(f.h0),d.putInt32(f.h1),d.putInt32(f.h2),d.putInt32(f.h3),d.putInt32(f.h4),d},n};var sa=null,jl=!1;function yg(){sa="\x80",sa+=Ue.util.fillString("\0",64),jl=!0}function Zl(e,t,r){for(var n,i,o,s,a,c,u,l,f=r.length();f>=64;){for(i=e.h0,o=e.h1,s=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<20;++l)n=t[l-3]^t[l-8]^t[l-14]^t[l-16],n=n<<1|n>>>31,t[l]=n,u=a^o&(s^a),n=(i<<5|i>>>27)+u+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<32;++l)n=t[l-3]^t[l-8]^t[l-14]^t[l-16],n=n<<1|n>>>31,t[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<40;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<60;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=o&s|a&(o^s),n=(i<<5|i>>>27)+u+c+2400959708+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<80;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=o^s^a,n=(i<<5|i>>>27)+u+c+3395469782+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,f-=64}}});var of=tt((dv,nf)=>{var Fe=ft();Lt();oi();ef();var rf=nf.exports=Fe.pkcs1=Fe.pkcs1||{};rf.encode_rsa_oaep=function(e,t,r){var n,i,o,s;typeof r=="string"?(n=r,i=arguments[3]||void 0,o=arguments[4]||void 0):r&&(n=r.label||void 0,i=r.seed||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(s=r.mgf1.md)),o?o.start():o=Fe.md.sha1.create(),s||(s=o);var a=Math.ceil(e.n.bitLength()/8),c=a-2*o.digestLength-2;if(t.length>c){var u=new Error("RSAES-OAEP input message length is too long.");throw u.length=t.length,u.maxLength=c,u}n||(n=""),o.update(n,"raw");for(var l=o.digest(),f="",d=c-t.length,p=0;p<d;p++)f+="\0";var h=l.getBytes()+f+""+t;if(!i)i=Fe.random.getBytes(o.digestLength);else if(i.length!==o.digestLength){var u=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=o.digestLength,u}var m=ro(i,a-o.digestLength-1,s),g=Fe.util.xorBytes(h,m,h.length),y=ro(g,o.digestLength,s),x=Fe.util.xorBytes(i,y,i.length);return"\0"+x+g};rf.decode_rsa_oaep=function(e,t,r){var n,i,o;typeof r=="string"?(n=r,i=arguments[3]||void 0):r&&(n=r.label||void 0,i=r.md||void 0,r.mgf1&&r.mgf1.md&&(o=r.mgf1.md));var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var g=new Error("RSAES-OAEP encoded message length is invalid.");throw g.length=t.length,g.expectedLength=s,g}if(i===void 0?i=Fe.md.sha1.create():i.start(),o||(o=i),s<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=t.charAt(0),u=t.substring(1,i.digestLength+1),l=t.substring(1+i.digestLength),f=ro(l,i.digestLength,o),d=Fe.util.xorBytes(u,f,u.length),p=ro(d,s-i.digestLength-1,o),h=Fe.util.xorBytes(l,p,l.length),m=h.substring(0,i.digestLength),g=c!=="\0",y=0;y<i.digestLength;++y)g|=a.charAt(y)!==m.charAt(y);for(var x=1,b=i.digestLength,_=i.digestLength;_<h.length;_++){var w=h.charCodeAt(_),S=w&1^1,D=x?65534:0;g|=w&D,x=x&S,b+=x}if(g||h.charCodeAt(b)!==1)throw new Error("Invalid RSAES-OAEP padding.");return h.substring(b+1)};function ro(e,t,r){r||(r=Fe.md.sha1.create());for(var n="",i=Math.ceil(t/r.digestLength),o=0;o<i;++o){var s=String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255);r.start(),r.update(e+s),n+=r.digest().getBytes()}return n.substring(0,t)}});var sf=tt((pv,aa)=>{var hr=ft();Lt();eo();oi();(function(){if(hr.prime){aa.exports=hr.prime;return}var e=aa.exports=hr.prime=hr.prime||{},t=hr.jsbn.BigInteger,r=[6,4,2,4,2,4,6,2],n=new t(null);n.fromInt(30);var i=function(f,d){return f|d};e.generateProbablePrime=function(f,d,p){typeof d=="function"&&(p=d,d={}),d=d||{};var h=d.algorithm||"PRIMEINC";typeof h=="string"&&(h={name:h}),h.options=h.options||{};var m=d.prng||hr.random,g={nextBytes:function(y){for(var x=m.getBytesSync(y.length),b=0;b<y.length;++b)y[b]=x.charCodeAt(b)}};if(h.name==="PRIMEINC")return o(f,g,h.options,p);throw new Error("Invalid prime generation algorithm: "+h.name)};function o(f,d,p,h){return"workers"in p?c(f,d,p,h):s(f,d,p,h)}function s(f,d,p,h){var m=u(f,d),g=0,y=l(m.bitLength());"millerRabinTests"in p&&(y=p.millerRabinTests);var x=10;"maxBlockTime"in p&&(x=p.maxBlockTime),a(m,f,d,g,y,x,h)}function a(f,d,p,h,m,g,y){var x=+new Date;do{if(f.bitLength()>d&&(f=u(d,p)),f.isProbablePrime(m))return y(null,f);f.dAddOffset(r[h++%8],0)}while(g<0||+new Date-x<g);hr.util.setImmediate(function(){a(f,d,p,h,m,g,y)})}function c(f,d,p,h){if(typeof Worker>"u")return s(f,d,p,h);var m=u(f,d),g=p.workers,y=p.workLoad||100,x=y*30/8,b=p.workerScript||"forge/prime.worker.js";if(g===-1)return hr.util.estimateCores(function(w,S){w&&(S=2),g=S-1,_()});_();function _(){g=Math.max(1,g);for(var w=[],S=0;S<g;++S)w[S]=new Worker(b);for(var D=g,S=0;S<g;++S)w[S].addEventListener("message",$);var P=!1;function $(H){if(!P){--D;var q=H.data;if(q.found){for(var J=0;J<w.length;++J)w[J].terminate();return P=!0,h(null,new t(q.prime,16))}m.bitLength()>f&&(m=u(f,d));var lt=m.toString(16);H.target.postMessage({hex:lt,workLoad:y}),m.dAddOffset(x,0)}}}}function u(f,d){var p=new t(f,d),h=f-1;return p.testBit(h)||p.bitwiseTo(t.ONE.shiftLeft(h),i,p),p.dAddOffset(31-p.mod(n).byteValue(),0),p}function l(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var io=tt((mv,df)=>{var V=ft();ii();eo();qi();of();sf();oi();Lt();typeof rt>"u"&&(rt=V.jsbn.BigInteger);var rt,ca=V.util.isNodejs?Qi():null,E=V.asn1,xe=V.util;V.pki=V.pki||{};df.exports=V.pki.rsa=V.rsa=V.rsa||{};var G=V.pki,xg=[6,4,2,4,2,4,6,2],bg={name:"PrivateKeyInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},vg={name:"RSAPrivateKey",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Eg={name:"RSAPublicKey",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},wg=V.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:E.Class.UNIVERSAL,type:E.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Sg={name:"DigestInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:E.Class.UNIVERSAL,type:E.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Ag=function(e){var t;if(e.algorithm in G.oids)t=G.oids[e.algorithm];else{var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=E.oidToDer(t).getBytes(),i=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[]),o=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[]);o.value.push(E.create(E.Class.UNIVERSAL,E.Type.OID,!1,n)),o.value.push(E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,""));var s=E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(o),i.value.push(s),E.toDer(i).getBytes()},ff=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(rt.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(rt.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var n;do n=new rt(V.util.bytesToHex(V.random.getBytes(t.n.bitLength()/8)),16);while(n.compareTo(t.n)>=0||!n.gcd(t.n).equals(rt.ONE));e=e.multiply(n.modPow(t.e,t.n)).mod(t.n);for(var i=e.mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);i.compareTo(o)<0;)i=i.add(t.p);var s=i.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return s=s.multiply(n.modInverse(t.n)).mod(t.n),s};G.rsa.encrypt=function(e,t,r){var n=r,i,o=Math.ceil(t.n.bitLength()/8);r!==!1&&r!==!0?(n=r===2,i=hf(e,t,r)):(i=V.util.createBuffer(),i.putBytes(e));for(var s=new rt(i.toHex(),16),a=ff(s,t,n),c=a.toString(16),u=V.util.createBuffer(),l=o-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(V.util.hexToBytes(c)),u.getBytes()};G.rsa.decrypt=function(e,t,r,n){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var o=new Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=i,o}var s=new rt(V.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var a=ff(s,t,r),c=a.toString(16),u=V.util.createBuffer(),l=i-Math.ceil(c.length/2);l>0;)u.putByte(0),--l;return u.putBytes(V.util.hexToBytes(c)),n!==!1?no(u.getBytes(),t,r):u.getBytes()};G.rsa.createKeyPairGenerationState=function(e,t,r){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,r=r||{};var n=r.prng||V.random,i={nextBytes:function(a){for(var c=n.getBytesSync(a.length),u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},o=r.algorithm||"PRIMEINC",s;if(o==="PRIMEINC")s={algorithm:o,state:0,bits:e,rng:i,eInt:t||65537,e:new rt(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+o);return s};G.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new rt(null);r.fromInt(30);for(var n=0,i=function(f,d){return f|d},o=+new Date,s,a=0;e.keys===null&&(t<=0||a<t);){if(e.state===0){var c=e.p===null?e.pBits:e.qBits,u=c-1;e.pqState===0?(e.num=new rt(c,e.rng),e.num.testBit(u)||e.num.bitwiseTo(rt.ONE.shiftLeft(u),i,e.num),e.num.dAddOffset(31-e.num.mod(r).byteValue(),0),n=0,++e.pqState):e.pqState===1?e.num.bitLength()>c?e.pqState=0:e.num.isProbablePrime(_g(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(xg[n++%8],0):e.pqState===2?e.pqState=e.num.subtract(rt.ONE).gcd(e.e).compareTo(rt.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(rt.ONE),e.q1=e.q.subtract(rt.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(rt.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var l=e.e.modInverse(e.phi);e.keys={privateKey:G.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:G.rsa.setPublicKey(e.n,e.e)}}s=+new Date,a+=s-o,o=s}return e.keys!==null};G.rsa.generateKeyPair=function(e,t,r,n){if(arguments.length===1?typeof e=="object"?(r=e,e=void 0):typeof e=="function"&&(n=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(n=t,t=void 0):typeof t!="number"&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof r=="function"&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},e===void 0&&(e=r.bits||2048),t===void 0&&(t=r.e||65537),!V.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(n){if(af("generateKeyPair"))return ca.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return n(a);n(null,{privateKey:G.privateKeyFromPem(u),publicKey:G.publicKeyFromPem(c)})});if(cf("generateKey")&&cf("exportKey"))return xe.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:lf(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return xe.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){n(a)}).then(function(a){if(a){var c=G.privateKeyFromAsn1(E.fromDer(V.util.createBuffer(a)));n(null,{privateKey:c,publicKey:G.setRsaPublicKey(c.n,c.e)})}});if(uf("generateKey")&&uf("exportKey")){var i=xe.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:lf(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=xe.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,d=G.privateKeyFromAsn1(E.fromDer(V.util.createBuffer(f)));n(null,{privateKey:d,publicKey:G.setRsaPublicKey(d.n,d.e)})},u.onerror=function(l){n(l)}},i.onerror=function(a){n(a)};return}}else if(af("generateKeyPairSync")){var o=ca.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:G.privateKeyFromPem(o.privateKey),publicKey:G.publicKeyFromPem(o.publicKey)}}}var s=G.rsa.createKeyPairGenerationState(e,t,r);if(!n)return G.rsa.stepKeyPairGenerationState(s,0),s.keys;Ig(s,r,n)};G.setRsaPublicKey=G.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(n,i,o){if(typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSAES-PKCS1-V1_5"),i==="RSAES-PKCS1-V1_5")i={encode:function(a,c,u){return hf(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return V.pkcs1.encode_rsa_oaep(c,a,o)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};else if(typeof i=="string")throw new Error('Unsupported encryption scheme: "'+i+'".');var s=i.encode(n,r,!0);return G.rsa.encrypt(s,r,!0)},r.verify=function(n,i,o,s){typeof o=="string"?o=o.toUpperCase():o===void 0&&(o="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),o==="RSASSA-PKCS1-V1_5"?o={verify:function(c,u){u=no(u,r,!0);var l=E.fromDer(u,{parseAllBytes:s._parseAllDigestBytes}),f={},d=[];if(!E.validate(l,Sg,f,d)){var p=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw p.errors=d,p}var h=E.derToOid(f.algorithmIdentifier);if(!(h===V.oids.md2||h===V.oids.md5||h===V.oids.sha1||h===V.oids.sha224||h===V.oids.sha256||h===V.oids.sha384||h===V.oids.sha512||h===V.oids["sha512-224"]||h===V.oids["sha512-256"])){var p=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw p.oid=h,p}if((h===V.oids.md2||h===V.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return c===f.digest}}:(o==="NONE"||o==="NULL"||o===null)&&(o={verify:function(c,u){return u=no(u,r,!0),c===u}});var a=G.rsa.decrypt(i,r,!0,!1);return o.verify(n,a,r.n.bitLength())},r};G.setRsaPrivateKey=G.rsa.setPrivateKey=function(e,t,r,n,i,o,s,a){var c={n:e,e:t,d:r,p:n,q:i,dP:o,dQ:s,qInv:a};return c.decrypt=function(u,l,f){typeof l=="string"?l=l.toUpperCase():l===void 0&&(l="RSAES-PKCS1-V1_5");var d=G.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:no};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(p,h){return V.pkcs1.decode_rsa_oaep(h,p,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(p){return p}};else throw new Error('Unsupported encryption scheme: "'+l+'".');return l.decode(d,c,!1)},c.sign=function(u,l){var f=!1;typeof l=="string"&&(l=l.toUpperCase()),l===void 0||l==="RSASSA-PKCS1-V1_5"?(l={encode:Ag},f=1):(l==="NONE"||l==="NULL"||l===null)&&(l={encode:function(){return u}},f=1);var d=l.encode(u,c.n.bitLength());return G.rsa.encrypt(d,c,f)},c};G.wrapRsaPrivateKey=function(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(0).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(G.oids.rsaEncryption).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(e).getBytes())])};G.privateKeyFromAsn1=function(e){var t={},r=[];if(E.validate(e,bg,t,r)&&(e=E.fromDer(V.util.createBuffer(t.privateKey))),t={},r=[],!E.validate(e,vg,t,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var i,o,s,a,c,u,l,f;return i=V.util.createBuffer(t.privateKeyModulus).toHex(),o=V.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=V.util.createBuffer(t.privateKeyPrivateExponent).toHex(),a=V.util.createBuffer(t.privateKeyPrime1).toHex(),c=V.util.createBuffer(t.privateKeyPrime2).toHex(),u=V.util.createBuffer(t.privateKeyExponent1).toHex(),l=V.util.createBuffer(t.privateKeyExponent2).toHex(),f=V.util.createBuffer(t.privateKeyCoefficient).toHex(),G.setRsaPrivateKey(new rt(i,16),new rt(o,16),new rt(s,16),new rt(a,16),new rt(c,16),new rt(u,16),new rt(l,16),new rt(f,16))};G.privateKeyToAsn1=G.privateKeyToRSAPrivateKey=function(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(0).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.n)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.e)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.d)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.p)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.q)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.dP)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.dQ)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.qInv))])};G.publicKeyFromAsn1=function(e){var t={},r=[];if(E.validate(e,wg,t,r)){var n=E.derToOid(t.publicKeyOid);if(n!==G.oids.rsaEncryption){var i=new Error("Cannot read public key. Unknown OID.");throw i.oid=n,i}e=t.rsaPublicKey}if(r=[],!E.validate(e,Eg,t,r)){var i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=r,i}var o=V.util.createBuffer(t.publicKeyModulus).toHex(),s=V.util.createBuffer(t.publicKeyExponent).toHex();return G.setRsaPublicKey(new rt(o,16),new rt(s,16))};G.publicKeyToAsn1=G.publicKeyToSubjectPublicKeyInfo=function(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(G.oids.rsaEncryption).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.BITSTRING,!1,[G.publicKeyToRSAPublicKey(e)])])};G.publicKeyToRSAPublicKey=function(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.n)),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,Ke(e.e))])};function hf(e,t,r){var n=V.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}n.putByte(0),n.putByte(r);var s=i-3-e.length,a;if(r===0||r===1){a=r===0?0:255;for(var c=0;c<s;++c)n.putByte(a)}else for(;s>0;){for(var u=0,l=V.random.getBytes(s),c=0;c<s;++c)a=l.charCodeAt(c),a===0?++u:n.putByte(a);s=u}return n.putByte(0),n.putBytes(e),n}function no(e,t,r,n){var i=Math.ceil(t.n.bitLength()/8),o=V.util.createBuffer(e),s=o.getByte(),a=o.getByte();if(s!==0||r&&a!==0&&a!==1||!r&&a!=2||r&&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(o.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(a===1)for(c=0;o.length()>1;){if(o.getByte()!==255){--o.read;break}++c}else if(a===2)for(c=0;o.length()>1;){if(o.getByte()===0){--o.read;break}++c}var l=o.getByte();if(l!==0||c!==i-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function Ig(e,t,r){typeof t=="function"&&(r=t,t={}),t=t||{};var n={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(n.prng=t.prng),i();function i(){o(e.pBits,function(a,c){if(a)return r(a);if(e.p=c,e.q!==null)return s(a,e.q);o(e.qBits,s)})}function o(a,c){V.prime.generateProbablePrime(a,n,c)}function s(a,c){if(a)return r(a);if(e.q=c,e.p.compareTo(e.q)<0){var u=e.p;e.p=e.q,e.q=u}if(e.p.subtract(rt.ONE).gcd(e.e).compareTo(rt.ONE)!==0){e.p=null,i();return}if(e.q.subtract(rt.ONE).gcd(e.e).compareTo(rt.ONE)!==0){e.q=null,o(e.qBits,s);return}if(e.p1=e.p.subtract(rt.ONE),e.q1=e.q.subtract(rt.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(rt.ONE)!==0){e.p=e.q=null,i();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,o(e.qBits,s);return}var l=e.e.modInverse(e.phi);e.keys={privateKey:G.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:G.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}}function Ke(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=V.util.hexToBytes(t);return r.length>1&&(r.charCodeAt(0)===0&&!(r.charCodeAt(1)&128)||r.charCodeAt(0)===255&&(r.charCodeAt(1)&128)===128)?r.substr(1):r}function _g(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function af(e){return V.util.isNodejs&&typeof ca[e]=="function"}function cf(e){return typeof xe.globalScope<"u"&&typeof xe.globalScope.crypto=="object"&&typeof xe.globalScope.crypto.subtle=="object"&&typeof xe.globalScope.crypto.subtle[e]=="function"}function uf(e){return typeof xe.globalScope<"u"&&typeof xe.globalScope.msCrypto=="object"&&typeof xe.globalScope.msCrypto.subtle=="object"&&typeof xe.globalScope.msCrypto.subtle[e]=="function"}function lf(e){for(var t=V.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n<t.length;++n)r[n]=t.charCodeAt(n);return r}});var bf=tt((gv,xf)=>{var M=ft();js();ii();wl();Or();qi();Cl();Bl();oi();ql();io();Lt();typeof pf>"u"&&(pf=M.jsbn.BigInteger);var pf,I=M.asn1,W=M.pki=M.pki||{};xf.exports=W.pbe=M.pbe=M.pbe||{};var Ur=W.oids,Cg={name:"EncryptedPrivateKeyInfo",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},Rg={name:"PBES2Algorithms",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},Tg={name:"pkcs-12PbeParams",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"iterations"}]};W.encryptPrivateKeyInfo=function(e,t,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var n=M.random.getBytesSync(r.saltSize),i=r.count,o=I.integerToDer(i),s,a,c;if(r.algorithm.indexOf("aes")===0||r.algorithm==="des"){var u,l,f;switch(r.algorithm){case"aes128":s=16,u=16,l=Ur["aes128-CBC"],f=M.aes.createEncryptionCipher;break;case"aes192":s=24,u=16,l=Ur["aes192-CBC"],f=M.aes.createEncryptionCipher;break;case"aes256":s=32,u=16,l=Ur["aes256-CBC"],f=M.aes.createEncryptionCipher;break;case"des":s=8,u=8,l=Ur.desCBC,f=M.des.createEncryptionCipher;break;default:var d=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw d.algorithm=r.algorithm,d}var p="hmacWith"+r.prfAlgorithm.toUpperCase(),h=yf(p),m=M.pkcs5.pbkdf2(t,n,i,s,h),g=M.random.getBytesSync(u),y=f(m);y.start(g),y.update(I.toDer(e)),y.finish(),c=y.output.getBytes();var x=Bg(n,o,s,p);a=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(Ur.pkcs5PBES2).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(Ur.pkcs5PBKDF2).getBytes()),x]),I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(l).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,g)])])])}else if(r.algorithm==="3des"){s=24;var b=new M.util.ByteBuffer(n),m=W.pbe.generatePkcs12Key(t,b,1,i,s),g=W.pbe.generatePkcs12Key(t,b,2,i,s),y=M.des.createEncryptionCipher(m);y.start(g),y.update(I.toDer(e)),y.finish(),c=y.output.getBytes(),a=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(Ur["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,n),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,o.getBytes())])])}else{var d=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw d.algorithm=r.algorithm,d}var _=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[a,I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,c)]);return _};W.decryptPrivateKeyInfo=function(e,t){var r=null,n={},i=[];if(!I.validate(e,Cg,n,i)){var o=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=I.derToOid(n.encryptionOid),a=W.pbe.getCipher(s,n.encryptionParams,t),c=M.util.createBuffer(n.encryptedData);return a.update(c),a.finish()&&(r=I.fromDer(a.output)),r};W.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:I.toDer(e).getBytes()};return M.pem.encode(r,{maxline:t})};W.encryptedPrivateKeyFromPem=function(e){var t=M.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return I.fromDer(t.body)};W.encryptRsaPrivateKey=function(e,t,r){if(r=r||{},!r.legacy){var n=W.wrapRsaPrivateKey(W.privateKeyToAsn1(e));return n=W.encryptPrivateKeyInfo(n,t,r),W.encryptedPrivateKeyToPem(n)}var i,o,s,a;switch(r.algorithm){case"aes128":i="AES-128-CBC",s=16,o=M.random.getBytesSync(16),a=M.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,o=M.random.getBytesSync(16),a=M.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,o=M.random.getBytesSync(16),a=M.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,o=M.random.getBytesSync(8),a=M.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,o=M.random.getBytesSync(8),a=M.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw c.algorithm=r.algorithm,c}var u=M.pbe.opensslDeriveBytes(t,o.substr(0,8),s),l=a(u);l.start(o),l.update(I.toDer(W.privateKeyToAsn1(e))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:M.util.bytesToHex(o).toUpperCase()},body:l.output.getBytes()};return M.pem.encode(f)};W.decryptRsaPrivateKey=function(e,t){var r=null,n=M.pem.decode(e)[0];if(n.type!=="ENCRYPTED PRIVATE KEY"&&n.type!=="PRIVATE KEY"&&n.type!=="RSA PRIVATE KEY"){var i=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(n.procType&&n.procType.type==="ENCRYPTED"){var o,s;switch(n.dekInfo.algorithm){case"DES-CBC":o=8,s=M.des.createDecryptionCipher;break;case"DES-EDE3-CBC":o=24,s=M.des.createDecryptionCipher;break;case"AES-128-CBC":o=16,s=M.aes.createDecryptionCipher;break;case"AES-192-CBC":o=24,s=M.aes.createDecryptionCipher;break;case"AES-256-CBC":o=32,s=M.aes.createDecryptionCipher;break;case"RC2-40-CBC":o=5,s=function(f){return M.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":o=8,s=function(f){return M.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":o=16,s=function(f){return M.rc2.createDecryptionCipher(f,128)};break;default:var i=new Error('Could not decrypt private key; unsupported encryption algorithm "'+n.dekInfo.algorithm+'".');throw i.algorithm=n.dekInfo.algorithm,i}var a=M.util.hexToBytes(n.dekInfo.parameters),c=M.pbe.opensslDeriveBytes(t,a.substr(0,8),o),u=s(c);if(u.start(a),u.update(M.util.createBuffer(n.body)),u.finish())r=u.output.getBytes();else return r}else r=n.body;return n.type==="ENCRYPTED PRIVATE KEY"?r=W.decryptPrivateKeyInfo(I.fromDer(r),t):r=I.fromDer(r),r!==null&&(r=W.privateKeyFromAsn1(r)),r};W.pbe.generatePkcs12Key=function(e,t,r,n,i,o){var s,a;if(typeof o>"u"||o===null){if(!("sha1"in M.md))throw new Error('"sha1" hash algorithm unavailable.');o=M.md.sha1.create()}var c=o.digestLength,u=o.blockLength,l=new M.util.ByteBuffer,f=new M.util.ByteBuffer;if(e!=null){for(a=0;a<e.length;a++)f.putInt16(e.charCodeAt(a));f.putInt16(0)}var d=f.length(),p=t.length(),h=new M.util.ByteBuffer;h.fillWithByte(r,u);var m=u*Math.ceil(p/u),g=new M.util.ByteBuffer;for(a=0;a<m;a++)g.putByte(t.at(a%p));var y=u*Math.ceil(d/u),x=new M.util.ByteBuffer;for(a=0;a<y;a++)x.putByte(f.at(a%d));var b=g;b.putBuffer(x);for(var _=Math.ceil(i/c),w=1;w<=_;w++){var S=new M.util.ByteBuffer;S.putBytes(h.bytes()),S.putBytes(b.bytes());for(var D=0;D<n;D++)o.start(),o.update(S.getBytes()),S=o.digest();var P=new M.util.ByteBuffer;for(a=0;a<u;a++)P.putByte(S.at(a%c));var $=Math.ceil(p/u)+Math.ceil(d/u),H=new M.util.ByteBuffer;for(s=0;s<$;s++){var q=new M.util.ByteBuffer(b.getBytes(u)),J=511;for(a=P.length()-1;a>=0;a--)J=J>>8,J+=P.at(a)+q.at(a),q.setAt(a,J&255);H.putBuffer(q)}b=H,l.putBuffer(S)}return l.truncate(l.length()-i),l};W.pbe.getCipher=function(e,t,r){switch(e){case W.oids.pkcs5PBES2:return W.pbe.getCipherForPBES2(e,t,r);case W.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case W.oids["pbewithSHAAnd40BitRC2-CBC"]:return W.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}};W.pbe.getCipherForPBES2=function(e,t,r){var n={},i=[];if(!I.validate(t,Rg,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}if(e=I.derToOid(n.kdfOid),e!==W.oids.pkcs5PBKDF2){var o=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw o.oid=e,o.supportedOids=["pkcs5PBKDF2"],o}if(e=I.derToOid(n.encOid),e!==W.oids["aes128-CBC"]&&e!==W.oids["aes192-CBC"]&&e!==W.oids["aes256-CBC"]&&e!==W.oids["des-EDE3-CBC"]&&e!==W.oids.desCBC){var o=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw o.oid=e,o.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],o}var s=n.kdfSalt,a=M.util.createBuffer(n.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(W.oids[e]){case"aes128-CBC":c=16,u=M.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=M.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=M.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=M.des.createDecryptionCipher;break;case"desCBC":c=8,u=M.des.createDecryptionCipher;break}var l=gf(n.prfOid),f=M.pkcs5.pbkdf2(r,s,a,c,l),d=n.encIv,p=u(f);return p.start(d),p};W.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},i=[];if(!I.validate(t,Tg,n,i)){var o=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=M.util.createBuffer(n.salt),a=M.util.createBuffer(n.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(e){case W.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=M.des.startDecrypting;break;case W.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(m,g){var y=M.rc2.createDecryptionCipher(m,40);return y.start(g,null),y};break;default:var o=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw o.oid=e,o}var f=gf(n.prfOid),d=W.pbe.generatePkcs12Key(r,s,1,a,c,f);f.start();var p=W.pbe.generatePkcs12Key(r,s,2,a,u,f);return l(d,p)};W.pbe.opensslDeriveBytes=function(e,t,r,n){if(typeof n>"u"||n===null){if(!("md5"in M.md))throw new Error('"md5" hash algorithm unavailable.');n=M.md.md5.create()}t===null&&(t="");for(var i=[mf(n,e+t)],o=16,s=1;o<r;++s,o+=16)i.push(mf(n,i[s-1]+e+t));return i.join("").substr(0,r)};function mf(e,t){return e.start().update(t).digest().getBytes()}function gf(e){var t;if(!e)t="hmacWithSHA1";else if(t=W.oids[I.derToOid(e)],!t){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}return yf(t)}function yf(e){var t=M.md;switch(e){case"hmacWithSHA224":t=M.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function Bg(e,t,r,n){var i=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,e),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,t.getBytes())]);return n!=="hmacWithSHA1"&&i.value.push(I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M.util.hexToBytes(r.toString(16))),I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(W.oids[n]).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.NULL,!1,"")])),i}});var B0=tt((aA,T0)=>{var mt=ft();Or();Lt();var yi=T0.exports=mt.sha512=mt.sha512||{};mt.md.sha512=mt.md.algorithms.sha512=yi;var C0=mt.sha384=mt.sha512.sha384=mt.sha512.sha384||{};C0.create=function(){return yi.create("SHA-384")};mt.md.sha384=mt.md.algorithms.sha384=C0;mt.sha512.sha256=mt.sha512.sha256||{create:function(){return yi.create("SHA-512/256")}};mt.md["sha512/256"]=mt.md.algorithms["sha512/256"]=mt.sha512.sha256;mt.sha512.sha224=mt.sha512.sha224||{create:function(){return yi.create("SHA-512/224")}};mt.md["sha512/224"]=mt.md.algorithms["sha512/224"]=mt.sha512.sha224;yi.create=function(e){if(R0||tx(),typeof e>"u"&&(e="SHA-512"),!(e in Wr))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=Wr[e],r=null,n=mt.util.createBuffer(),i=new Array(80),o=0;o<80;++o)i[o]=new Array(2);var s=64;switch(e){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var a={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];for(var c=a.messageLengthSize/4,u=0;u<c;++u)a.fullMessageLength.push(0);n=mt.util.createBuffer(),r=new Array(t.length);for(var u=0;u<t.length;++u)r[u]=t[u].slice(0);return a},a.start(),a.update=function(c,u){u==="utf8"&&(c=mt.util.encodeUtf8(c));var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;return n.putBytes(c),_0(r,i,n),(n.read>2048||n.length()===0)&&n.compact(),a},a.digest=function(){var c=mt.util.createBuffer();c.putBytes(n.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(mc.substr(0,a.blockLength-l));for(var f,d,p=a.fullMessageLength[0]*8,h=0;h<a.fullMessageLength.length-1;++h)f=a.fullMessageLength[h+1]*8,d=f/4294967296>>>0,p+=d,c.putInt32(p>>>0),p=f>>>0;c.putInt32(p);for(var m=new Array(r.length),h=0;h<r.length;++h)m[h]=r[h].slice(0);_0(m,i,c);var g=mt.util.createBuffer(),y;e==="SHA-512"?y=m.length:e==="SHA-384"?y=m.length-2:y=m.length-4;for(var h=0;h<y;++h)g.putInt32(m[h][0]),(h!==y-1||e!=="SHA-512/224")&&g.putInt32(m[h][1]);return g},a};var mc=null,R0=!1,gc=null,Wr=null;function tx(){mc="\x80",mc+=mt.util.fillString("\0",128),gc=[[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]],Wr={},Wr["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],Wr["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],Wr["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],Wr["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],R0=!0}function _0(e,t,r){for(var n,i,o,s,a,c,u,l,f,d,p,h,m,g,y,x,b,_,w,S,D,P,$,H,q,J,lt,zt,T,O,L,N,C,U,K,z=r.length();z>=128;){for(T=0;T<16;++T)t[T][0]=r.getInt32()>>>0,t[T][1]=r.getInt32()>>>0;for(;T<80;++T)N=t[T-2],O=N[0],L=N[1],n=((O>>>19|L<<13)^(L>>>29|O<<3)^O>>>6)>>>0,i=((O<<13|L>>>19)^(L<<3|O>>>29)^(O<<26|L>>>6))>>>0,U=t[T-15],O=U[0],L=U[1],o=((O>>>1|L<<31)^(O>>>8|L<<24)^O>>>7)>>>0,s=((O<<31|L>>>1)^(O<<24|L>>>8)^(O<<25|L>>>7))>>>0,C=t[T-7],K=t[T-16],L=i+C[1]+s+K[1],t[T][0]=n+C[0]+o+K[0]+(L/4294967296>>>0)>>>0,t[T][1]=L>>>0;for(m=e[0][0],g=e[0][1],y=e[1][0],x=e[1][1],b=e[2][0],_=e[2][1],w=e[3][0],S=e[3][1],D=e[4][0],P=e[4][1],$=e[5][0],H=e[5][1],q=e[6][0],J=e[6][1],lt=e[7][0],zt=e[7][1],T=0;T<80;++T)u=((D>>>14|P<<18)^(D>>>18|P<<14)^(P>>>9|D<<23))>>>0,l=((D<<18|P>>>14)^(D<<14|P>>>18)^(P<<23|D>>>9))>>>0,f=(q^D&($^q))>>>0,d=(J^P&(H^J))>>>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,p=(m&y|b&(m^y))>>>0,h=(g&x|_&(g^x))>>>0,L=zt+l+d+gc[T][1]+t[T][1],n=lt+u+f+gc[T][0]+t[T][0]+(L/4294967296>>>0)>>>0,i=L>>>0,L=c+h,o=a+p+(L/4294967296>>>0)>>>0,s=L>>>0,lt=q,zt=J,q=$,J=H,$=D,H=P,L=S+i,D=w+n+(L/4294967296>>>0)>>>0,P=L>>>0,w=b,S=_,b=y,_=x,y=m,x=g,L=i+s,m=n+o+(L/4294967296>>>0)>>>0,g=L>>>0;L=e[0][1]+g,e[0][0]=e[0][0]+m+(L/4294967296>>>0)>>>0,e[0][1]=L>>>0,L=e[1][1]+x,e[1][0]=e[1][0]+y+(L/4294967296>>>0)>>>0,e[1][1]=L>>>0,L=e[2][1]+_,e[2][0]=e[2][0]+b+(L/4294967296>>>0)>>>0,e[2][1]=L>>>0,L=e[3][1]+S,e[3][0]=e[3][0]+w+(L/4294967296>>>0)>>>0,e[3][1]=L>>>0,L=e[4][1]+P,e[4][0]=e[4][0]+D+(L/4294967296>>>0)>>>0,e[4][1]=L>>>0,L=e[5][1]+H,e[5][0]=e[5][0]+$+(L/4294967296>>>0)>>>0,e[5][1]=L>>>0,L=e[6][1]+J,e[6][0]=e[6][0]+q+(L/4294967296>>>0)>>>0,e[6][1]=L>>>0,L=e[7][1]+zt,e[7][0]=e[7][0]+lt+(L/4294967296>>>0)>>>0,e[7][1]=L>>>0,z-=128}}});var Tc=tt((w4,nh)=>{var Pn=1e3,Nn=Pn*60,On=Nn*60,Zr=On*24,Cx=Zr*7,Rx=Zr*365.25;nh.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return Tx(e);if(r==="number"&&isFinite(e))return t.long?Lx(e):Bx(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Tx(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Rx;case"weeks":case"week":case"w":return r*Cx;case"days":case"day":case"d":return r*Zr;case"hours":case"hour":case"hrs":case"hr":case"h":return r*On;case"minutes":case"minute":case"mins":case"min":case"m":return r*Nn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Pn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function Bx(e){var t=Math.abs(e);return t>=Zr?Math.round(e/Zr)+"d":t>=On?Math.round(e/On)+"h":t>=Nn?Math.round(e/Nn)+"m":t>=Pn?Math.round(e/Pn)+"s":e+"ms"}function Lx(e){var t=Math.abs(e);return t>=Zr?Bo(e,t,Zr,"day"):t>=On?Bo(e,t,On,"hour"):t>=Nn?Bo(e,t,Nn,"minute"):t>=Pn?Bo(e,t,Pn,"second"):e+" ms"}function Bo(e,t,r,n){var i=t>=r*1.5;return Math.round(e/r)+" "+n+(i?"s":"")}});var oh=tt((S4,ih)=>{function Dx(e){r.debug=r,r.default=r,r.coerce=c,r.disable=o,r.enable=i,r.enabled=s,r.humanize=Tc(),r.destroy=u,Object.keys(e).forEach(l=>{r[l]=e[l]}),r.names=[],r.skips=[],r.formatters={};function t(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=t;function r(l){let f,d=null,p,h;function m(...g){if(!m.enabled)return;let y=m,x=Number(new Date),b=x-(f||x);y.diff=b,y.prev=f,y.curr=x,f=x,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let _=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(S,D)=>{if(S==="%%")return"%";_++;let P=r.formatters[D];if(typeof P=="function"){let $=g[_];S=P.call(y,$),g.splice(_,1),_--}return S}),r.formatArgs.call(y,g),(y.log||r.log).apply(y,g)}return m.namespace=l,m.useColors=r.useColors(),m.color=r.selectColor(l),m.extend=n,m.destroy=r.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(p!==r.namespaces&&(p=r.namespaces,h=r.enabled(l)),h),set:g=>{d=g}}),typeof r.init=="function"&&r.init(m),m}function n(l,f){let d=r(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),p=d.length;for(f=0;f<p;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?r.skips.push(new RegExp("^"+l.slice(1)+"$")):r.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=r.skips.length;f<d;f++)if(r.skips[f].test(l))return!1;for(f=0,d=r.names.length;f<d;f++)if(r.names[f].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 r.enable(r.load()),r}ih.exports=Dx});var Bc=tt((me,Lo)=>{me.formatArgs=Nx;me.save=Ox;me.load=kx;me.useColors=Px;me.storage=Mx();me.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();me.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 Px(){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 Nx(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Lo.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),e.splice(n,0,t)}me.log=console.debug||console.log||(()=>{});function Ox(e){try{e?me.storage.setItem("debug",e):me.storage.removeItem("debug")}catch{}}function kx(){let e;try{e=me.storage.getItem("debug")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function Mx(){try{return localStorage}catch{}}Lo.exports=oh()(me);var{formatters:Ux}=Lo.exports;Ux.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Lh=tt((b_,Xc)=>{"use strict";var v2=Object.prototype.hasOwnProperty,se="~";function Ri(){}Object.create&&(Ri.prototype=Object.create(null),new Ri().__proto__||(se=!1));function E2(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function Bh(e,t,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var o=new E2(r,n||e,i),s=se?se+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],o]:e._events[s].push(o):(e._events[s]=o,e._eventsCount++),e}function Vo(e,t){--e._eventsCount===0?e._events=new Ri:delete e._events[t]}function ne(){this._events=new Ri,this._eventsCount=0}ne.prototype.eventNames=function(){var t=[],r,n;if(this._eventsCount===0)return t;for(n in r=this._events)v2.call(r,n)&&t.push(se?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(r)):t};ne.prototype.listeners=function(t){var r=se?se+t:t,n=this._events[r];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};ne.prototype.listenerCount=function(t){var r=se?se+t:t,n=this._events[r];return n?n.fn?1:n.length:0};ne.prototype.emit=function(t,r,n,i,o,s){var a=se?se+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,o),!0;case 6:return c.fn.call(c.context,r,n,i,o,s),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,p;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,r);break;case 3:c[f].fn.call(c[f].context,r,n);break;case 4:c[f].fn.call(c[f].context,r,n,i);break;default:if(!l)for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c[f].fn.apply(c[f].context,l)}}return!0};ne.prototype.on=function(t,r,n){return Bh(this,t,r,n,!1)};ne.prototype.once=function(t,r,n){return Bh(this,t,r,n,!0)};ne.prototype.removeListener=function(t,r,n,i){var o=se?se+t:t;if(!this._events[o])return this;if(!r)return Vo(this,o),this;var s=this._events[o];if(s.fn)s.fn===r&&(!i||s.once)&&(!n||s.context===n)&&Vo(this,o);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==r||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:Vo(this,o)}return this};ne.prototype.removeAllListeners=function(t){var r;return t?(r=se?se+t:t,this._events[r]&&Vo(this,r)):(this._events=new Ri,this._eventsCount=0),this};ne.prototype.off=ne.prototype.removeListener;ne.prototype.addListener=ne.prototype.on;ne.prefixed=se;ne.EventEmitter=ne;typeof Xc<"u"&&(Xc.exports=ne)});var du=tt((UC,Hh)=>{"use strict";function $h(e,t){for(let r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}function U2(e,t,r){if(!e||typeof e=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof t=="object"&&(r=t,t=""),t&&(r.code=t);try{return $h(e,r)}catch{r.message=e.message,r.stack=e.stack;let i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),$h(new i,r)}}Hh.exports=U2});var Xh=tt(Di=>{(function(){var e,t,r,n,i,o,s,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[u,l,f,d].join(".")},s=function(c){var u,l,f,d,p,h;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=t(c),p=h[0],l=h[1],c=c.substring(l),u.push(p)}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")}},r=function(c){return c.charCodeAt(0)},n=r("0"),o=r("a"),i=r("A"),t=function(c){var u,l,f,d,p;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),p=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(r(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+r(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+r(c[f])-i)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===p)throw new Error("empty octet");return[d,f]},e=function(){function c(u,l){var f,d,p,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(h=u.split("/",2),u=h[0],l=h[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=s(l)}catch(m){throw f=m,new Error("Invalid mask: "+l)}for(d=p=32;p>=0;d=--p)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(u)&this.maskLong)>>>0}catch(m){throw f=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):(s(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=s(this.first),f=s(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Di.ip2long=s,Di.long2ip=a,Di.Netmask=e}).call(Di)});var td=tt((jh,ts)=>{(function(e){"use strict";let t="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${t}\\.${t}\\.${t}\\.${t}$`,"i"),threeOctet:new RegExp(`^${t}\\.${t}\\.${t}$`,"i"),twoOctet:new RegExp(`^${t}\\.${t}$`,"i"),longValue:new RegExp(`^${t}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${t}\\.${t}\\.${t}\\.${t}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${t}\\.${t}\\.${t}\\.${t}(${o})?$`,"i")};function c(p,h){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let m=0,g=-1,y=(p.match(a.zoneIndex)||[])[0],x,b;for(y&&(y=y.substring(1),p=p.replace(/%.+$/,""));(g=p.indexOf(":",g+1))>=0;)m++;if(p.substr(0,2)==="::"&&m--,p.substr(-2,2)==="::"&&m--,m>h)return null;for(b=h-m,x=":";b--;)x+="0:";return p=p.replace("::",x),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),h=function(){let _=p.split(":"),w=[];for(let S=0;S<_.length;S++)w.push(parseInt(_[S],16));return w}(),{parts:h,zoneId:y}}function u(p,h,m,g){if(p.length!==h.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let y=0,x;for(;g>0;){if(x=m-g,x<0&&(x=0),p[y]>>x!==h[y]>>x)return!1;g-=m,y+=1}return!0}function l(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function f(p,h){for(;p.length<h;)p=`0${p}`;return p}let d={};d.IPv4=function(){function p(h){if(h.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let m,g;for(m=0;m<h.length;m++)if(g=h[m],!(0<=g&&g<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=h}return p.prototype.SpecialRanges={unspecified:[[new p([0,0,0,0]),8]],broadcast:[[new p([255,255,255,255]),32]],multicast:[[new p([224,0,0,0]),4]],linkLocal:[[new p([169,254,0,0]),16]],loopback:[[new p([127,0,0,0]),8]],carrierGradeNat:[[new p([100,64,0,0]),10]],private:[[new p([10,0,0,0]),8],[new p([172,16,0,0]),12],[new p([192,168,0,0]),16]],reserved:[[new p([192,0,0,0]),24],[new p([192,0,2,0]),24],[new p([192,88,99,0]),24],[new p([198,18,0,0]),15],[new p([198,51,100,0]),24],[new p([203,0,113,0]),24],[new p([240,0,0,0]),4]]},p.prototype.kind=function(){return"ipv4"},p.prototype.match=function(h,m){let g;if(m===void 0&&(g=h,h=g[0],m=g[1]),h.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,h.octets,8,m)},p.prototype.prefixLengthFromSubnetMask=function(){let h=0,m=!1,g={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},y,x,b;for(y=3;y>=0;y-=1)if(x=this.octets[y],x in g){if(b=g[x],m&&b!==0)return null;b!==8&&(m=!0),h+=b}else return null;return 32-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return d.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p}(),d.IPv4.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),m=h[0].toByteArray(),g=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],x=0;for(;x<4;)y.push(parseInt(m[x],10)|parseInt(g[x],10)^255),x++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.isIPv4=function(p){return this.parser(p)!==null},d.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch{return!1}},d.IPv4.isValidFourPartDecimal=function(p){return!!(d.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},d.IPv4.networkAddressFromCIDR=function(p){let h,m,g,y,x;try{for(h=this.parseCIDR(p),g=h[0].toByteArray(),x=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],m=0;m<4;)y.push(parseInt(g[m],10)&parseInt(x[m],10)),m++;return new this(y)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},d.IPv4.parse=function(p){let h=this.parser(p);if(h===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(h)},d.IPv4.parseCIDR=function(p){let h;if(h=p.match(/^(.+)\/(\d+)$/)){let m=parseInt(h[2]);if(m>=0&&m<=32){let g=[this.parse(h[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")},d.IPv4.parser=function(p){let h,m,g;if(h=p.match(r.fourOctet))return function(){let y=h.slice(1,6),x=[];for(let b=0;b<y.length;b++)m=y[b],x.push(l(m));return x}();if(h=p.match(r.longValue)){if(g=l(h[1]),g>4294967295||g<0)throw new Error("ipaddr: address outside defined range");return function(){let y=[],x;for(x=0;x<=24;x+=8)y.push(g>>x&255);return y}().reverse()}else return(h=p.match(r.twoOctet))?function(){let y=h.slice(1,4),x=[];if(g=l(y[1]),g>16777215||g<0)throw new Error("ipaddr: address outside defined range");return x.push(l(y[0])),x.push(g>>16&255),x.push(g>>8&255),x.push(g&255),x}():(h=p.match(r.threeOctet))?function(){let y=h.slice(1,5),x=[];if(g=l(y[2]),g>65535||g<0)throw new Error("ipaddr: address outside defined range");return x.push(l(y[0])),x.push(l(y[1])),x.push(g>>8&255),x.push(g&255),x}():null},d.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let h=[0,0,0,0],m=0,g=Math.floor(p/8);for(;m<g;)h[m]=255,m++;return g<4&&(h[g]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.IPv6=function(){function p(h,m){let g,y;if(h.length===16)for(this.parts=[],g=0;g<=14;g+=2)this.parts.push(h[g]<<8|h[g+1]);else if(h.length===8)this.parts=h;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 p.prototype.SpecialRanges={unspecified:[new p([0,0,0,0,0,0,0,0]),128],linkLocal:[new p([65152,0,0,0,0,0,0,0]),10],multicast:[new p([65280,0,0,0,0,0,0,0]),8],loopback:[new p([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new p([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new p([0,0,0,0,0,65535,0,0]),96],rfc6145:[new p([0,0,0,0,65535,0,0,0]),96],rfc6052:[new p([100,65435,0,0,0,0,0,0]),96],"6to4":[new p([8194,0,0,0,0,0,0,0]),16],teredo:[new p([8193,0,0,0,0,0,0,0]),32],reserved:[[new p([8193,3512,0,0,0,0,0,0]),32]],benchmarking:[new p([8193,2,0,0,0,0,0,0]),48],amt:[new p([8193,3,0,0,0,0,0,0]),32],as112v6:[new p([8193,4,274,0,0,0,0,0]),48],deprecated:[new p([8193,16,0,0,0,0,0,0]),28],orchid2:[new p([8193,32,0,0,0,0,0,0]),28]},p.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},p.prototype.kind=function(){return"ipv6"},p.prototype.match=function(h,m){let g;if(m===void 0&&(g=h,h=g[0],m=g[1]),h.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,h.parts,16,m)},p.prototype.prefixLengthFromSubnetMask=function(){let h=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,x;for(let b=7;b>=0;b-=1)if(y=this.parts[b],y in g){if(x=g[y],m&&x!==0)return null;x!==16&&(m=!0),h+=x}else return null;return 128-h},p.prototype.range=function(){return d.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let h,m=[],g=this.parts;for(let y=0;y<g.length;y++)h=g[y],m.push(h>>8),m.push(h&255);return m},p.prototype.toFixedLengthString=function(){let h=function(){let g=[];for(let y=0;y<this.parts.length;y++)g.push(f(this.parts[y].toString(16),4));return g}.call(this).join(":"),m="";return this.zoneId&&(m=`%${this.zoneId}`),h+m},p.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let h=this.parts.slice(-2),m=h[0],g=h[1];return new d.IPv4([m>>8,m&255,g>>8,g&255])},p.prototype.toNormalizedString=function(){let h=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}`),h+m},p.prototype.toRFC5952String=function(){let h=/((^|:)(0(:|$)){2,})/g,m=this.toNormalizedString(),g=0,y=-1,x;for(;x=h.exec(m);)x[0].length>y&&(g=x.index,y=x[0].length);return y<0?m:`${m.substring(0,g)}::${m.substring(g+y)}`},p.prototype.toString=function(){return this.toRFC5952String()},p}(),d.IPv6.broadcastAddressFromCIDR=function(p){try{let h=this.parseCIDR(p),m=h[0].toByteArray(),g=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],x=0;for(;x<16;)y.push(parseInt(m[x],10)|parseInt(g[x],10)^255),x++;return new this(y)}catch(h){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${h})`)}},d.IPv6.isIPv6=function(p){return this.parser(p)!==null},d.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{let h=this.parser(p);return new this(h.parts,h.zoneId),!0}catch{return!1}},d.IPv6.networkAddressFromCIDR=function(p){let h,m,g,y,x;try{for(h=this.parseCIDR(p),g=h[0].toByteArray(),x=this.subnetMaskFromPrefixLength(h[1]).toByteArray(),y=[],m=0;m<16;)y.push(parseInt(g[m],10)&parseInt(x[m],10)),m++;return new this(y)}catch(b){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${b})`)}},d.IPv6.parse=function(p){let h=this.parser(p);if(h.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(h.parts,h.zoneId)},d.IPv6.parseCIDR=function(p){let h,m,g;if((m=p.match(/^(.+)\/(\d+)$/))&&(h=parseInt(m[2]),h>=0&&h<=128))return g=[this.parse(m[1]),h],Object.defineProperty(g,"toString",{value:function(){return this.join("/")}}),g;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},d.IPv6.parser=function(p){let h,m,g,y,x,b;if(g=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${g[1]}`);if(a.native.test(p))return c(p,8);if((g=p.match(a.transitional))&&(b=g[6]||"",h=c(g[1].slice(0,-1)+b,6),h.parts)){for(x=[parseInt(g[2]),parseInt(g[3]),parseInt(g[4]),parseInt(g[5])],m=0;m<x.length;m++)if(y=x[m],!(0<=y&&y<=255))return null;return h.parts.push(x[0]<<8|x[1]),h.parts.push(x[2]<<8|x[3]),{parts:h.parts,zoneId:h.zoneId}}return null},d.IPv6.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>128)throw new Error("ipaddr: invalid IPv6 prefix length");let h=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=0,g=Math.floor(p/8);for(;m<g;)h[m]=255,m++;return g<16&&(h[g]=Math.pow(2,p%8)-1<<8-p%8),new this(h)},d.fromByteArray=function(p){let h=p.length;if(h===4)return new d.IPv4(p);if(h===16)return new d.IPv6(p);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},d.isValid=function(p){return d.IPv6.isValid(p)||d.IPv4.isValid(p)},d.parse=function(p){if(d.IPv6.isValid(p))return d.IPv6.parse(p);if(d.IPv4.isValid(p))return d.IPv4.parse(p);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},d.parseCIDR=function(p){try{return d.IPv6.parseCIDR(p)}catch{try{return d.IPv4.parseCIDR(p)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},d.process=function(p){let h=this.parse(p);return h.kind()==="ipv6"&&h.isIPv4MappedAddress()?h.toIPv4Address():h},d.subnetMatch=function(p,h,m){let g,y,x,b;m==null&&(m="unicast");for(y in h)if(Object.prototype.hasOwnProperty.call(h,y)){for(x=h[y],x[0]&&!(x[0]instanceof Array)&&(x=[x]),g=0;g<x.length;g++)if(b=x[g],p.kind()===b[0].kind()&&p.match.apply(p,b))return y}return m},typeof ts<"u"&&ts.exports?ts.exports=d:e.ipaddr=d})(jh)});var yd=tt((NR,gd)=>{"use strict";gd.exports=md;var ob=Tc(),Lr=md.prototype,sb=new Date%1e9;function ab(){return(Math.random()*1e9>>>0)+sb++}function md(e){e=e||{},this.id=e.id||ab(),this.max=e.max||1/0,this.items=e.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(e.lastModified||new Date);for(var t,r,n=this.items.length;n--;)t=this.items[n],r=new Date(t.expires)-new Date,this._lookup[t.key]=t,r>0?this.expire(t.key,r):r<=0&&this.delete(t.key)}Lr.has=function(e){return e in this._lookup};Lr.get=function(e){if(!this.has(e))return null;var t=this._lookup[e];return t.refresh&&this.expire(e,t.refresh),this.items.splice(this.items.indexOf(t),1),this.items.push(t),t.value};Lr.meta=function(e){if(!this.has(e))return null;var t=this._lookup[e];return"meta"in t?t.meta:null};Lr.set=function(e,t,r){var n=this._lookup[e],i=this._lookup[e]={key:e,value:t};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++),r&&("ttl"in r&&this.expire(e,r.ttl),"meta"in r&&(i.meta=r.meta),r.refresh&&(i.refresh=r.ttl)),this};Lr.delete=function(e){var t=this._lookup[e];return t?(this.lastModified=new Date,this.items.splice(this.items.indexOf(t),1),clearTimeout(t.timeout),delete this._lookup[e],this.size--,this):!1};Lr.expire=function(e,t){var r=t||0,n=this._lookup[e];if(!n)return this;if(typeof r=="string"&&(r=ob(t)),typeof r!="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),r),n.expires=Number(new Date)+r,this};Lr.clear=function(){for(var e=this.items.length;e--;)this.delete(this.items[e].key);return this};Lr.toJSON=function(){for(var e=new Array(this.items.length),t,r=e.length;r--;)t=this.items[r],e[r]={key:t.key,meta:t.meta,value:t.value,expires:t.expires,refresh:t.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:e}}});var wd=tt((VR,Ed)=>{"use strict";Ed.exports=e=>{if(Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}});var Rd=tt((_d,Cd)=>{"use strict";var cs=wd(),{hasOwnProperty:Ad}=Object.prototype,{propertyIsEnumerable:lb}=Object,Wn=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),fb=_d,Sd={concatArrays:!1,ignoreUndefined:!1},us=e=>{let t=[];for(let r in e)Ad.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(e);for(let n of r)lb.call(e,n)&&t.push(n)}return t};function Qn(e){return Array.isArray(e)?hb(e):cs(e)?db(e):e}function hb(e){let t=e.slice(0,0);return us(e).forEach(r=>{Wn(t,r,Qn(e[r]))}),t}function db(e){let t=Object.getPrototypeOf(e)===null?Object.create(null):{};return us(e).forEach(r=>{Wn(t,r,Qn(e[r]))}),t}var Id=(e,t,r,n)=>(r.forEach(i=>{typeof t[i]>"u"&&n.ignoreUndefined||(i in e&&e[i]!==Object.getPrototypeOf(e)?Wn(e,i,Ru(e[i],t[i],n)):Wn(e,i,Qn(t[i])))}),e),pb=(e,t,r)=>{let n=e.slice(0,0),i=0;return[e,t].forEach(o=>{let s=[];for(let a=0;a<o.length;a++)Ad.call(o,a)&&(s.push(String(a)),o===e?Wn(n,i++,o[a]):Wn(n,i++,Qn(o[a])));n=Id(n,o,us(o).filter(a=>!s.includes(a)),r)}),n};function Ru(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?pb(e,t,r):!cs(t)||!cs(e)?Qn(t):Id(e,t,us(t),r)}Cd.exports=function(...e){let t=Ru(Qn(Sd),this!==fb&&this||{},Sd),r={_:{}};for(let n of e)if(n!==void 0){if(!cs(n))throw new TypeError("`"+n+"` is not an Option Object");r=Ru(r,{_:n},t)}return r._}});var $b={};Ut($b,{createLibp2p:()=>zb});var p4=St(ii(),1),m4=St(bf(),1);var vf=Symbol.for("@libp2p/connection");var ua=Symbol.for("@libp2p/content-routing");var la=Symbol.for("@libp2p/peer-discovery");var fa=Symbol.for("@libp2p/peer-id");function oo(e){return e!=null&&!!e[fa]}var ha=Symbol.for("@libp2p/peer-routing");var Ef="keep-alive";var wf;(function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"})(wf||(wf={}));var Iv=Symbol.for("@libp2p/transport");var dr;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(dr||(dr={}));var pr=class e extends Error{code;type;constructor(t="The operation was aborted"){super(t),this.code=e.code,this.type=e.type}static code="ABORT_ERR";static type="aborted"},A=class extends Error{code;props;constructor(t,r,n){super(t),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}},so=class extends AggregateError{code;props;constructor(t,r,n,i){super(t,r),this.code=n,this.name=i?.name??"AggregateCodeError",this.props=i??{}}};var ao="ERR_TIMEOUT";var Fr=class extends EventTarget{#t=new Map;listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let i=this.#t.get(t);i==null&&(i=[],this.#t.set(t,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let i=this.#t.get(t);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#t.set(t,i))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:i})=>!i),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r={}){return this.dispatchEvent(new pa(t,r))}},da=class extends Event{detail;constructor(t,r){super(t,r),this.detail=r?.detail}},pa=globalThis.CustomEvent??da;var be=(e,...t)=>{try{[...t]}catch{}};function Sf(e){return e!=null&&typeof e.start=="function"&&typeof e.stop=="function"}var _x=St(ft(),1);function mr(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var ba={};Ut(ba,{base10:()=>kg});var iE=new Uint8Array(0);function Af(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function Ze(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function If(e){return new TextEncoder().encode(e)}function _f(e){return new TextDecoder().decode(e)}function Lg(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,x=h.length;y!==x&&h[y]===0;)y++,m++;for(var b=(x-y)*l+1>>>0,_=new Uint8Array(b);y!==x;){for(var w=h[y],S=0,D=b-1;(w!==0||S<g)&&D!==-1;D--,S++)w+=256*_[D]>>>0,_[D]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");g=S,y++}for(var P=b-g;P!==b&&_[P]===0;)P++;for(var $=c.repeat(m);P<b;++P)$+=e.charAt(_[P]);return $}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var x=(h.length-m)*u+1>>>0,b=new Uint8Array(x);h[m];){var _=r[h.charCodeAt(m)];if(_===255)return;for(var w=0,S=x-1;(_!==0||w<y)&&S!==-1;S--,w++)_+=a*b[S]>>>0,b[S]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=w,m++}if(h[m]!==" "){for(var D=x-y;D!==x&&b[D]===0;)D++;for(var P=new Uint8Array(g+(x-D)),$=g;D!==x;)P[$++]=b[D++];return P}}}function p(h){var m=d(h);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:p}}var Dg=Lg,Pg=Dg,Rf=Pg;var ma=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},ga=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Tf(this,t)}},ya=class{decoders;constructor(t){this.decoders=t}or(t){return Tf(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Tf(e,t){return new ya({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var xa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,i){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new ma(t,r,n),this.decoder=new ga(t,r,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function xn({name:e,prefix:t,encode:r,decode:n}){return new xa(e,t,r,n)}function gr({name:e,prefix:t,alphabet:r}){let{encode:n,decode:i}=Rf(r,e);return xn({prefix:t,name:e,encode:n,decode:o=>Ze(i(o))})}function Ng(e,t,r,n){let i={};for(let l=0;l<t.length;++l)i[t[l]]=l;let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let f=i[e[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Og(e,t,r){let n=t[t.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>r;)s-=r,o+=t[i&a>>s];if(s!==0&&(o+=t[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o}function At({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return xn({prefix:t,name:e,encode(i){return Og(i,n,r)},decode(i){return Ng(i,n,r,e)}})}var kg=gr({prefix:"9",name:"base10",alphabet:"0123456789"});var va={};Ut(va,{base16:()=>Mg,base16upper:()=>Ug});var Mg=At({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ug=At({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ea={};Ut(Ea,{base2:()=>Fg});var Fg=At({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wa={};Ut(wa,{base256emoji:()=>$g});var Bf=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}"),Kg=Bf.reduce((e,t,r)=>(e[r]=t,e),[]),Vg=Bf.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function qg(e){return e.reduce((t,r)=>(t+=Kg[r],t),"")}function zg(e){let t=[];for(let r of e){let n=Vg[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var $g=xn({prefix:"\u{1F680}",name:"base256emoji",encode:qg,decode:zg});var Sa={};Ut(Sa,{base32:()=>he,base32hex:()=>Wg,base32hexpad:()=>Xg,base32hexpadupper:()=>Zg,base32hexupper:()=>Qg,base32pad:()=>Gg,base32padupper:()=>Yg,base32upper:()=>Hg,base32z:()=>Jg});var he=At({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hg=At({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gg=At({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yg=At({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wg=At({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qg=At({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xg=At({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zg=At({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jg=At({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Aa={};Ut(Aa,{base36:()=>jg,base36upper:()=>ty});var jg=gr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ty=gr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ia={};Ut(Ia,{base58btc:()=>vt,base58flickr:()=>ey});var vt=gr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ey=gr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ca={};Ut(Ca,{base64:()=>bn,base64pad:()=>ry,base64url:()=>_a,base64urlpad:()=>ny});var bn=At({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ry=At({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_a=At({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ny=At({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ra={};Ut(Ra,{base8:()=>iy});var iy=At({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ta={};Ut(Ta,{identity:()=>oy});var oy=xn({prefix:"\0",name:"identity",encode:e=>_f(e),decode:e=>If(e)});var vE=new TextEncoder,EE=new TextDecoder;var La={};Ut(La,{identity:()=>yr});var cy=Pf,Lf=128,uy=127,ly=~uy,fy=Math.pow(2,31);function Pf(e,t,r){t=t||[],r=r||0;for(var n=r;e>=fy;)t[r++]=e&255|Lf,e/=128;for(;e&ly;)t[r++]=e&255|Lf,e>>>=7;return t[r]=e|0,Pf.bytes=r-n+1,t}var hy=Ba,dy=128,Df=127;function Ba(e,n){var r=0,n=n||0,i=0,o=n,s,a=e.length;do{if(o>=a)throw Ba.bytes=0,new RangeError("Could not decode varint");s=e[o++],r+=i<28?(s&Df)<<i:(s&Df)*Math.pow(2,i),i+=7}while(s>=dy);return Ba.bytes=o-n,r}var py=Math.pow(2,7),my=Math.pow(2,14),gy=Math.pow(2,21),yy=Math.pow(2,28),xy=Math.pow(2,35),by=Math.pow(2,42),vy=Math.pow(2,49),Ey=Math.pow(2,56),wy=Math.pow(2,63),Sy=function(e){return e<py?1:e<my?2:e<gy?3:e<yy?4:e<xy?5:e<by?6:e<vy?7:e<Ey?8:e<wy?9:10},Ay={encode:cy,decode:hy,encodingLength:Sy},Iy=Ay,ai=Iy;function ci(e,t=0){return[ai.decode(e,t),ai.decode.bytes]}function vn(e,t,r=0){return ai.encode(e,t,r),t}function En(e){return ai.encodingLength(e)}function Ve(e,t){let r=t.byteLength,n=En(e),i=n+En(r),o=new Uint8Array(i+r);return vn(e,o,0),vn(r,o,n),o.set(t,i),new wn(e,r,t,o)}function Kr(e){let t=Ze(e),[r,n]=ci(t),[i,o]=ci(t.subarray(n)),s=t.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new wn(r,i,s,t)}function Nf(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Af(e.bytes,r.bytes)}}var wn=class{code;size;digest;bytes;constructor(t,r,n,i){this.code=t,this.size=r,this.digest=n,this.bytes=i}};var Of=0,_y="identity",kf=Ze;function Cy(e){return Ve(Of,kf(e))}var yr={code:Of,name:_y,encode:kf,digest:Cy};var Na={};Ut(Na,{sha256:()=>Gt,sha512:()=>Ry});function Pa({name:e,code:t,encode:r}){return new Da(e,t,r)}var Da=class{name;code;encode;constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Ve(this.code,r):r.then(n=>Ve(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Uf(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var Gt=Pa({name:"sha2-256",code:18,encode:Uf("SHA-256")}),Ry=Pa({name:"sha2-512",code:19,encode:Uf("SHA-512")});function Ff(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return By(r,Oa(e),t??vt.encoder);default:return Ly(r,Oa(e),t??he.encoder)}}var Kf=new WeakMap;function Oa(e){let t=Kf.get(e);if(t==null){let r=new Map;return Kf.set(e,r),r}return t}var _e=class e{code;version;multihash;bytes;"/";constructor(t,r,n,i){this.code=r,this.version=t,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:t,multihash:r}=this;if(t!==ui)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Dy)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}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:t,digest:r}=this.multihash,n=Ve(t,r);return e.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(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Nf(t.multihash,n.multihash)}toString(t){return Ff(this,t)}toJSON(){return{"/":Ff(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new e(n,i,o,s??Vf(n,i,o.bytes))}else if(r[Py]===!0){let{version:n,multihash:i,code:o}=r,s=Kr(i);return e.create(n,o,s)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==ui)throw new Error(`Version 0 CID must use dag-pb (code: ${ui}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let i=Vf(t,r,n.bytes);return new e(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,ui,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,i=Ze(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new wn(r.multihashCode,r.digestSize,o,i);return[r.version===0?e.createV0(s):e.createV1(r.codec,s),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[f,d]=ci(t.subarray(r));return r+=d,f},i=n(),o=ui;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,r){let[n,i]=Ty(t,r),o=e.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Oa(o).set(n,t),o}};function Ty(e,t){switch(e[0]){case"Q":{let r=t??vt;return[vt.prefix,r.decode(`${vt.prefix}${e}`)]}case vt.prefix:{let r=t??vt;return[vt.prefix,r.decode(e)]}case he.prefix:{let r=t??he;return[he.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function By(e,t,r){let{prefix:n}=r;if(n!==vt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i}function Ly(e,t,r){let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i}var ui=112,Dy=18;function Vf(e,t,r){let n=En(e),i=n+En(t),o=new Uint8Array(i+r.byteLength);return vn(e,o,0),vn(t,o,n),o.set(r,i),o}var Py=Symbol.for("@ipld/js-cid/CID");var xr={...Ta,...Ea,...Ra,...ba,...va,...Sa,...Aa,...Ia,...Ca,...wa},qE={...Na,...La};function Je(e=0){return globalThis.Buffer?.alloc!=null?mr(globalThis.Buffer.alloc(e)):new Uint8Array(e)}function jt(e=0){return globalThis.Buffer?.allocUnsafe!=null?mr(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function zf(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var qf=zf("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),ka=zf("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=jt(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Ny={utf8:qf,"utf-8":qf,hex:xr.base16,latin1:ka,ascii:ka,binary:ka,...xr},uo=Ny;function Y(e,t="utf8"){let r=uo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?mr(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}var pc={};Ut(pc,{Ed25519PrivateKey:()=>Yr,Ed25519PublicKey:()=>gi,generateKeyPair:()=>X1,generateKeyPairFromSeed:()=>I0,unmarshalEd25519PrivateKey:()=>W1,unmarshalEd25519PublicKey:()=>Q1});function Et(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}var iw=St(Lt(),1),ow=St(eo(),1),$f=St(ft(),1);function Ct(e,t){if(globalThis.Buffer!=null)return mr(globalThis.Buffer.concat(e,t));t==null&&(t=e.reduce((i,o)=>i+o.length,0));let r=jt(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return mr(r)}function it(e,t="utf8"){let r=uo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function Ce(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return it(r,"base64url")}function de(e){let t=Hf(e);return new $f.default.jsbn.BigInteger(it(t,"base16"),16)}function Hf(e,t){let r=Y(e,"base64urlpad");if(t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return r}function ve(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}function Gf(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Oy(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function Ma(e,...t){if(!Oy(e))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Yf(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Gf(e.outputLen),Gf(e.blockLen)}function Sn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Wf(e,t){Ma(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var lo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qf(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}var fo=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Re=(e,t)=>e<<32-t|e>>>t,ky=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ky)throw new Error("Non little-endian hardware is not supported");function Ua(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function li(e){if(typeof e=="string"&&(e=Ua(e)),!Qf(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ho(...e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(!Qf(i))throw new Error("Uint8Array expected");t+=i.length}let r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){let o=e[n];r.set(o,i),i+=o.length}return r}var An=class{clone(){return this._cloneInto()}},dw={}.toString;function po(e){let t=n=>e().update(li(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function In(e=32){if(lo&&typeof lo.getRandomValues=="function")return lo.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function My(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}var _n=class extends An{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=fo(this.buffer)}update(t){Sn(this);let{view:r,buffer:n,blockLen:i}=this;t=li(t);let o=t.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=fo(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Sn(this),Wf(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;My(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=fo(t),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 f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.length=i,t.pos=a,t.finished=o,t.destroyed=s,i%r&&t.buffer.set(n),t}};var mo=BigInt(4294967295),Fa=BigInt(32);function Xf(e,t=!1){return t?{h:Number(e&mo),l:Number(e>>Fa&mo)}:{h:Number(e>>Fa&mo)|0,l:Number(e&mo)|0}}function Uy(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:o,l:s}=Xf(e[i],t);[r[i],n[i]]=[o,s]}return[r,n]}var Fy=(e,t)=>BigInt(e>>>0)<<Fa|BigInt(t>>>0),Ky=(e,t,r)=>e>>>r,Vy=(e,t,r)=>e<<32-r|t>>>r,qy=(e,t,r)=>e>>>r|t<<32-r,zy=(e,t,r)=>e<<32-r|t>>>r,$y=(e,t,r)=>e<<64-r|t>>>r-32,Hy=(e,t,r)=>e>>>r-32|t<<64-r,Gy=(e,t)=>t,Yy=(e,t)=>e,Wy=(e,t,r)=>e<<r|t>>>32-r,Qy=(e,t,r)=>t<<r|e>>>32-r,Xy=(e,t,r)=>t<<r-32|e>>>64-r,Zy=(e,t,r)=>e<<r-32|t>>>64-r;function Jy(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var jy=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),t1=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,e1=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),r1=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,n1=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),i1=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;var o1={fromBig:Xf,split:Uy,toBig:Fy,shrSH:Ky,shrSL:Vy,rotrSH:qy,rotrSL:zy,rotrBH:$y,rotrBL:Hy,rotr32H:Gy,rotr32L:Yy,rotlSH:Wy,rotlSL:Qy,rotlBH:Xy,rotlBL:Zy,add:Jy,add3L:jy,add3H:t1,add4L:e1,add4H:r1,add5H:i1,add5L:n1},Q=o1;var[s1,a1]=Q.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),br=new Uint32Array(80),vr=new Uint32Array(80),Ka=class extends _n{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:p,Gl:h,Hh:m,Hl:g}=this;return[t,r,n,i,o,s,a,c,u,l,f,d,p,h,m,g]}set(t,r,n,i,o,s,a,c,u,l,f,d,p,h,m,g){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=p|0,this.Gl=h|0,this.Hh=m|0,this.Hl=g|0}process(t,r){for(let b=0;b<16;b++,r+=4)br[b]=t.getUint32(r),vr[b]=t.getUint32(r+=4);for(let b=16;b<80;b++){let _=br[b-15]|0,w=vr[b-15]|0,S=Q.rotrSH(_,w,1)^Q.rotrSH(_,w,8)^Q.shrSH(_,w,7),D=Q.rotrSL(_,w,1)^Q.rotrSL(_,w,8)^Q.shrSL(_,w,7),P=br[b-2]|0,$=vr[b-2]|0,H=Q.rotrSH(P,$,19)^Q.rotrBH(P,$,61)^Q.shrSH(P,$,6),q=Q.rotrSL(P,$,19)^Q.rotrBL(P,$,61)^Q.shrSL(P,$,6),J=Q.add4L(D,q,vr[b-7],vr[b-16]),lt=Q.add4H(J,S,H,br[b-7],br[b-16]);br[b]=lt|0,vr[b]=J|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:p,Fl:h,Gh:m,Gl:g,Hh:y,Hl:x}=this;for(let b=0;b<80;b++){let _=Q.rotrSH(f,d,14)^Q.rotrSH(f,d,18)^Q.rotrBH(f,d,41),w=Q.rotrSL(f,d,14)^Q.rotrSL(f,d,18)^Q.rotrBL(f,d,41),S=f&p^~f&m,D=d&h^~d&g,P=Q.add5L(x,w,D,a1[b],vr[b]),$=Q.add5H(P,y,_,S,s1[b],br[b]),H=P|0,q=Q.rotrSH(n,i,28)^Q.rotrBH(n,i,34)^Q.rotrBH(n,i,39),J=Q.rotrSL(n,i,28)^Q.rotrBL(n,i,34)^Q.rotrBL(n,i,39),lt=n&o^n&a^o&a,zt=i&s^i&c^s&c;y=m|0,x=g|0,m=p|0,g=h|0,p=f|0,h=d|0,{h:f,l:d}=Q.add(u|0,l|0,$|0,H|0),u=a|0,l=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let T=Q.add3L(H,J,zt);n=Q.add3H(T,$,q,lt),i=T|0}({h:n,l:i}=Q.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=Q.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=Q.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Q.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=Q.add(this.Eh|0,this.El|0,f|0,d|0),{h:p,l:h}=Q.add(this.Fh|0,this.Fl|0,p|0,h|0),{h:m,l:g}=Q.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:x}=Q.add(this.Hh|0,this.Hl|0,y|0,x|0),this.set(n,i,o,s,a,c,u,l,f,d,p,h,m,g,y,x)}roundClean(){br.fill(0),vr.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Va=po(()=>new Ka);var yo={};Ut(yo,{bitGet:()=>p1,bitLen:()=>d1,bitMask:()=>fi,bitSet:()=>m1,bytesToHex:()=>tr,bytesToNumberBE:()=>er,bytesToNumberLE:()=>Er,concatBytes:()=>rr,createHmacDrbg:()=>$a,ensureBytes:()=>It,equalBytes:()=>f1,hexToBytes:()=>qr,hexToNumber:()=>za,isBytes:()=>Te,numberToBytesBE:()=>wr,numberToBytesLE:()=>zr,numberToHexUnpadded:()=>t0,numberToVarBytesBE:()=>l1,utf8ToBytes:()=>h1,validateObject:()=>qe});var jf=BigInt(0),go=BigInt(1),c1=BigInt(2);function Te(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}var u1=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function tr(e){if(!Te(e))throw new Error("Uint8Array expected");let t="";for(let r=0;r<e.length;r++)t+=u1[e[r]];return t}function t0(e){let t=e.toString(16);return t.length&1?`0${t}`:t}function za(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}var je={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Zf(e){if(e>=je._0&&e<=je._9)return e-je._0;if(e>=je._A&&e<=je._F)return e-(je._A-10);if(e>=je._a&&e<=je._f)return e-(je._a-10)}function qr(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Zf(e.charCodeAt(o)),a=Zf(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function er(e){return za(tr(e))}function Er(e){if(!Te(e))throw new Error("Uint8Array expected");return za(tr(Uint8Array.from(e).reverse()))}function wr(e,t){return qr(e.toString(16).padStart(t*2,"0"))}function zr(e,t){return wr(e,t).reverse()}function l1(e){return qr(t0(e))}function It(e,t,r){let n;if(typeof t=="string")try{n=qr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(Te(t))n=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${e} expected ${r} bytes, got ${i}`);return n}function rr(...e){let t=0;for(let i=0;i<e.length;i++){let o=e[i];if(!Te(o))throw new Error("Uint8Array expected");t+=o.length}let r=new Uint8Array(t),n=0;for(let i=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function f1(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function h1(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function d1(e){let t;for(t=0;e>jf;e>>=go,t+=1);return t}function p1(e,t){return e>>BigInt(t)&go}var m1=(e,t,r)=>e|(r?go:jf)<<BigInt(t),fi=e=>(c1<<BigInt(e-1))-go,qa=e=>new Uint8Array(e),Jf=e=>Uint8Array.from(e);function $a(e,t,r){if(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");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=qa(e),i=qa(e),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...f)=>r(i,n,...f),c=(f=qa())=>{i=a(Jf([0]),f),n=a(),f.length!==0&&(i=a(Jf([1]),f),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let p=n.slice();d.push(p),f+=n.length}return rr(...d)};return(f,d)=>{s(),c(f);let p;for(;!(p=d(u()));)c();return s(),p}}var g1={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||Te(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function qe(e,t,r={}){let n=(i,o,s)=>{let a=g1[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);let c=e[i];if(!(s&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(let[i,o]of Object.entries(t))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return e}var kt=BigInt(0),yt=BigInt(1),$r=BigInt(2),y1=BigInt(3),Ha=BigInt(4),e0=BigInt(5),r0=BigInt(8),x1=BigInt(9),b1=BigInt(16);function ht(e,t){let r=e%t;return r>=kt?r:t+r}function v1(e,t,r){if(r<=kt||t<kt)throw new Error("Expected power/modulo > 0");if(r===yt)return kt;let n=yt;for(;t>kt;)t&yt&&(n=n*e%r),e=e*e%r,t>>=yt;return n}function xt(e,t,r){let n=e;for(;t-- >kt;)n*=n,n%=r;return n}function xo(e,t){if(e===kt||t<=kt)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ht(e,t),n=t,i=kt,o=yt,s=yt,a=kt;for(;r!==kt;){let u=n/r,l=n%r,f=i-s*u,d=o-a*u;n=r,r=l,i=s,o=a,s=f,a=d}if(n!==yt)throw new Error("invert: does not exist");return ht(i,t)}function E1(e){let t=(e-yt)/$r,r,n,i;for(r=e-yt,n=0;r%$r===kt;r/=$r,n++);for(i=$r;i<e&&v1(i,t,e)!==e-yt;i++);if(n===1){let s=(e+yt)/Ha;return function(c,u){let l=c.pow(u,s);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let o=(r+yt)/$r;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,i),r),f=a.pow(c,o),d=a.pow(c,r);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let p=1;for(let m=a.sqr(d);p<u&&!a.eql(m,a.ONE);p++)m=a.sqr(m);let h=a.pow(l,yt<<BigInt(u-p-1));l=a.sqr(h),f=a.mul(f,h),d=a.mul(d,l),u=p}return f}}function w1(e){if(e%Ha===y1){let t=(e+yt)/Ha;return function(n,i){let o=n.pow(i,t);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(e%r0===e0){let t=(e-e0)/r0;return function(n,i){let o=n.mul(i,$r),s=n.pow(o,t),a=n.mul(i,s),c=n.mul(n.mul(a,$r),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return e%b1,E1(e)}var n0=(e,t)=>(ht(e,t)&yt)===yt,S1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ga(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=S1.reduce((n,i)=>(n[i]="function",n),t);return qe(e,r)}function A1(e,t,r){if(r<kt)throw new Error("Expected power > 0");if(r===kt)return e.ONE;if(r===yt)return t;let n=e.ONE,i=t;for(;r>kt;)r&yt&&(n=e.mul(n,i)),i=e.sqr(i),r>>=yt;return n}function I1(e,t){let r=new Array(t.length),n=t.reduce((o,s,a)=>e.is0(s)?o:(r[a]=o,e.mul(o,s)),e.ONE),i=e.inv(n);return t.reduceRight((o,s,a)=>e.is0(s)?o:(r[a]=e.mul(o,r[a]),e.mul(o,s)),i),r}function Ya(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function bo(e,t,r=!1,n={}){if(e<=kt)throw new Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:o}=Ya(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=w1(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:o,MASK:fi(i),ZERO:kt,ONE:yt,create:c=>ht(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return kt<=c&&c<e},is0:c=>c===kt,isOdd:c=>(c&yt)===yt,neg:c=>ht(-c,e),eql:(c,u)=>c===u,sqr:c=>ht(c*c,e),add:(c,u)=>ht(c+u,e),sub:(c,u)=>ht(c-u,e),mul:(c,u)=>ht(c*u,e),pow:(c,u)=>A1(a,c,u),div:(c,u)=>ht(c*xo(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>xo(c,e),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>I1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?zr(c,o):wr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return r?Er(c):er(c)}});return Object.freeze(a)}function i0(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");let r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function o0(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Wa(e){let t=o0(e);return t+Math.ceil(t/2)}function s0(e,t,r=!1){let n=e.length,i=o0(t),o=Wa(t);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?er(e):Er(e),a=ht(s,t-yt)+yt;return r?zr(a,i):wr(a,i)}var C1=BigInt(0),Qa=BigInt(1);function vo(e,t){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(t/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=e.ZERO,a=i;for(;o>C1;)o&Qa&&(s=s.add(a)),a=a.double(),o>>=Qa;return s},precomputeWindow(i,o){let{windows:s,windowSize:a}=n(o),c=[],u=i,l=u;for(let f=0;f<s;f++){l=u,c.push(l);for(let d=1;d<a;d++)l=l.add(u),c.push(l);u=l.double()}return c},wNAF(i,o,s){let{windows:a,windowSize:c}=n(i),u=e.ZERO,l=e.BASE,f=BigInt(2**i-1),d=2**i,p=BigInt(i);for(let h=0;h<a;h++){let m=h*c,g=Number(s&f);s>>=p,g>c&&(g-=d,s+=Qa);let y=m,x=m+Math.abs(g)-1,b=h%2!==0,_=g<0;g===0?l=l.add(r(b,o[y])):u=u.add(r(_,o[x]))}return{p:u,f:l}},wNAFCached(i,o,s,a){let c=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&o.set(i,a(u))),this.wNAF(c,u,s)}}}function hi(e){return Ga(e.Fp),qe(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ya(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var Be=BigInt(0),pe=BigInt(1),Eo=BigInt(2),R1=BigInt(8),T1={zip215:!0};function B1(e){let t=hi(e);return qe(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function wo(e){let t=B1(e),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:a,h:c}=t,u=Eo<<BigInt(a*8)-pe,l=r.create,f=t.uvRatio||((N,C)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(C))}}catch{return{isValid:!1,value:Be}}}),d=t.adjustScalarBytes||(N=>N),p=t.domain||((N,C,U)=>{if(C.length||U)throw new Error("Contexts/pre-hash are not supported");return N}),h=N=>typeof N=="bigint"&&Be<N,m=(N,C)=>h(N)&&h(C)&&N<C,g=N=>N===Be||m(N,u);function y(N,C){if(m(N,C))return N;throw new Error(`Expected valid scalar < ${C}, got ${typeof N} ${N}`)}function x(N){return N===Be?N:y(N,n)}let b=new Map;function _(N){if(!(N instanceof w))throw new Error("ExtendedPoint expected")}class w{constructor(C,U,K,z){if(this.ex=C,this.ey=U,this.ez=K,this.et=z,!g(C))throw new Error("x required");if(!g(U))throw new Error("y required");if(!g(K))throw new Error("z required");if(!g(z))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof w)throw new Error("extended point not allowed");let{x:U,y:K}=C||{};if(!g(U)||!g(K))throw new Error("invalid affine point");return new w(U,K,pe,l(U*K))}static normalizeZ(C){let U=r.invertBatch(C.map(K=>K.ez));return C.map((K,z)=>K.toAffine(U[z])).map(w.fromAffine)}_setWindowSize(C){this._WINDOW_SIZE=C,b.delete(this)}assertValidity(){let{a:C,d:U}=t;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:z,ez:X,et:j}=this,ct=l(K*K),et=l(z*z),ot=l(X*X),Bt=l(ot*ot),wt=l(ct*C),$t=l(ot*l(wt+et)),Ht=l(Bt+l(U*l(ct*et)));if($t!==Ht)throw new Error("bad point: equation left != right (1)");let Ot=l(K*z),Jt=l(X*j);if(Ot!==Jt)throw new Error("bad point: equation left != right (2)")}equals(C){_(C);let{ex:U,ey:K,ez:z}=this,{ex:X,ey:j,ez:ct}=C,et=l(U*ct),ot=l(X*z),Bt=l(K*ct),wt=l(j*z);return et===ot&&Bt===wt}is0(){return this.equals(w.ZERO)}negate(){return new w(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:C}=t,{ex:U,ey:K,ez:z}=this,X=l(U*U),j=l(K*K),ct=l(Eo*l(z*z)),et=l(C*X),ot=U+K,Bt=l(l(ot*ot)-X-j),wt=et+j,$t=wt-ct,Ht=et-j,Ot=l(Bt*$t),Jt=l(wt*Ht),Ye=l(Bt*Ht),Pr=l($t*wt);return new w(Ot,Jt,Pr,Ye)}add(C){_(C);let{a:U,d:K}=t,{ex:z,ey:X,ez:j,et:ct}=this,{ex:et,ey:ot,ez:Bt,et:wt}=C;if(U===BigInt(-1)){let Qu=l((X-z)*(ot+et)),Xu=l((X+z)*(ot-et)),Ks=l(Xu-Qu);if(Ks===Be)return this.double();let Zu=l(j*Eo*wt),Ju=l(ct*Eo*Bt),ju=Ju+Zu,tl=Xu+Qu,el=Ju-Zu,Zd=l(ju*Ks),Jd=l(tl*el),jd=l(ju*el),tp=l(Ks*tl);return new w(Zd,Jd,tp,jd)}let $t=l(z*et),Ht=l(X*ot),Ot=l(ct*K*wt),Jt=l(j*Bt),Ye=l((z+X)*(et+ot)-$t-Ht),Pr=Jt-Ot,ti=Jt+Ot,Wu=l(Ht-U*$t),Yd=l(Ye*Pr),Wd=l(ti*Wu),Qd=l(Ye*Wu),Xd=l(Pr*ti);return new w(Yd,Wd,Xd,Qd)}subtract(C){return this.add(C.negate())}wNAF(C){return P.wNAFCached(this,b,C,w.normalizeZ)}multiply(C){let{p:U,f:K}=this.wNAF(y(C,n));return w.normalizeZ([U,K])[0]}multiplyUnsafe(C){let U=x(C);return U===Be?D:this.equals(D)||U===pe?this:this.equals(S)?this.wNAF(U).p:P.unsafeLadder(this,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,n).is0()}toAffine(C){let{ex:U,ey:K,ez:z}=this,X=this.is0();C==null&&(C=X?R1:r.inv(z));let j=l(U*C),ct=l(K*C),et=l(z*C);if(X)return{x:Be,y:pe};if(et!==pe)throw new Error("invZ was invalid");return{x:j,y:ct}}clearCofactor(){let{h:C}=t;return C===pe?this:this.multiplyUnsafe(C)}static fromHex(C,U=!1){let{d:K,a:z}=t,X=r.BYTES;C=It("pointHex",C,X);let j=C.slice(),ct=C[X-1];j[X-1]=ct&-129;let et=Er(j);et===Be||(U?y(et,u):y(et,r.ORDER));let ot=l(et*et),Bt=l(ot-pe),wt=l(K*ot-z),{isValid:$t,value:Ht}=f(Bt,wt);if(!$t)throw new Error("Point.fromHex: invalid y coordinate");let Ot=(Ht&pe)===pe,Jt=(ct&128)!==0;if(!U&&Ht===Be&&Jt)throw new Error("Point.fromHex: x=0 and x_0=1");return Jt!==Ot&&(Ht=l(-Ht)),w.fromAffine({x:Ht,y:et})}static fromPrivateKey(C){return q(C).point}toRawBytes(){let{x:C,y:U}=this.toAffine(),K=zr(U,r.BYTES);return K[K.length-1]|=C&pe?128:0,K}toHex(){return tr(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,pe,l(t.Gx*t.Gy)),w.ZERO=new w(Be,pe,pe,Be);let{BASE:S,ZERO:D}=w,P=vo(w,a*8);function $(N){return ht(N,n)}function H(N){return $(Er(N))}function q(N){let C=a;N=It("private key",N,C);let U=It("hashed private key",o(N),2*C),K=d(U.slice(0,C)),z=U.slice(C,2*C),X=H(K),j=S.multiply(X),ct=j.toRawBytes();return{head:K,prefix:z,scalar:X,point:j,pointBytes:ct}}function J(N){return q(N).pointBytes}function lt(N=new Uint8Array,...C){let U=rr(...C);return H(o(p(U,It("context",N),!!i)))}function zt(N,C,U={}){N=It("message",N),i&&(N=i(N));let{prefix:K,scalar:z,pointBytes:X}=q(C),j=lt(U.context,K,N),ct=S.multiply(j).toRawBytes(),et=lt(U.context,ct,X,N),ot=$(j+et*z);x(ot);let Bt=rr(ct,zr(ot,r.BYTES));return It("result",Bt,a*2)}let T=T1;function O(N,C,U,K=T){let{context:z,zip215:X}=K,j=r.BYTES;N=It("signature",N,2*j),C=It("message",C),i&&(C=i(C));let ct=Er(N.slice(j,2*j)),et,ot,Bt;try{et=w.fromHex(U,X),ot=w.fromHex(N.slice(0,j),X),Bt=S.multiplyUnsafe(ct)}catch{return!1}if(!X&&et.isSmallOrder())return!1;let wt=lt(z,ot.toRawBytes(),et.toRawBytes(),C);return ot.add(et.multiplyUnsafe(wt)).subtract(Bt).clearCofactor().equals(w.ZERO)}return S._setWindowSize(8),{CURVE:t,getPublicKey:J,sign:zt,verify:O,ExtendedPoint:w,utils:{getExtendedPublicKey:q,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,C=w.BASE){return C._setWindowSize(N),C.multiply(BigInt(3)),C}}}}var Za=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),a0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ow=BigInt(0),L1=BigInt(1),Xa=BigInt(2),D1=BigInt(5),c0=BigInt(10),P1=BigInt(20),N1=BigInt(40),u0=BigInt(80);function O1(e){let t=Za,n=e*e%t*e%t,i=xt(n,Xa,t)*n%t,o=xt(i,L1,t)*e%t,s=xt(o,D1,t)*o%t,a=xt(s,c0,t)*s%t,c=xt(a,P1,t)*a%t,u=xt(c,N1,t)*c%t,l=xt(u,u0,t)*u%t,f=xt(l,u0,t)*u%t,d=xt(f,c0,t)*s%t;return{pow_p_5_8:xt(d,Xa,t)*e%t,b2:n}}function k1(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function M1(e,t){let r=Za,n=ht(t*t*t,r),i=ht(n*n*t,r),o=O1(e*i).pow_p_5_8,s=ht(e*n*o,r),a=ht(t*s*s,r),c=s,u=ht(s*a0,r),l=a===e,f=a===ht(-e,r),d=a===ht(-e*a0,r);return l&&(s=c),(f||d)&&(s=u),n0(s,r)&&(s=ht(-s,r)),{isValid:l||f,value:s}}var nr=bo(Za,void 0,!0),Ja={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:nr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Va,randomBytes:In,adjustScalarBytes:k1,uvRatio:M1},Cn=wo(Ja);function l0(e,t,r){if(t.length>255)throw new Error("Context is too big");return ho(Ua("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}var kw=wo({...Ja,domain:l0}),Mw=wo({...Ja,domain:l0,prehash:Va});var U1=(nr.ORDER+BigInt(3))/BigInt(8),Uw=nr.pow(Xa,U1),Fw=nr.sqrt(nr.neg(nr.ONE)),Kw=(nr.ORDER-BigInt(5))/BigInt(8),Vw=BigInt(486662);var qw=i0(nr,nr.neg(BigInt(486664)));var zw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),$w=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Hw=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Gw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Yw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Rn=32,ir=64,So=32;function f0(){let e=Cn.utils.randomPrivateKey(),t=Cn.getPublicKey(e);return{privateKey:m0(e,t),publicKey:t}}function h0(e){if(e.length!==So)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=e,r=Cn.getPublicKey(t);return{privateKey:m0(t,r),publicKey:r}}function d0(e,t){let r=e.subarray(0,So);return Cn.sign(t instanceof Uint8Array?t:t.subarray(),r)}function p0(e,t,r){return Cn.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}function m0(e,t){let r=new Uint8Array(ir);for(let n=0;n<So;n++)r[n]=e[n],r[So+n]=t[n];return r}var ce={get(e=globalThis){let t=e.crypto;if(t==null||t.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/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var ja={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function tc(e){let t=e?.algorithm??"AES-GCM",r=e?.keyLength??16,n=e?.nonceLength??12,i=e?.digest??"SHA-256",o=e?.saltLength??16,s=e?.iterations??32767,a=ce.get();r*=8;async function c(f,d){let p=a.getRandomValues(new Uint8Array(o)),h=a.getRandomValues(new Uint8Array(n)),m={name:t,iv:h};typeof d=="string"&&(d=Y(d));let g;if(d.length===0){g=await a.subtle.importKey("jwk",ja,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},b=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,b,{name:t,length:r},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",ja,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},b=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,b,{name:t,length:r},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,f);return Ct([p,m.iv,new Uint8Array(y)])}async function u(f,d){let p=f.subarray(0,o),h=f.subarray(o,o+n),m=f.subarray(o+n),g={name:t,iv:h};typeof d=="string"&&(d=Y(d));let y;if(d.length===0)try{let b={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},_=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,_,{name:t,length:r},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",ja,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},_=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,_,{name:t,length:r},!0,["decrypt"])}let x=await a.subtle.decrypt(g,y,m);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function Tn(e,t){let n=await tc().encrypt(e,t);return bn.encode(n)}var ec=new Float32Array([-0]),Sr=new Uint8Array(ec.buffer);function y0(e,t,r){ec[0]=e,t[r]=Sr[0],t[r+1]=Sr[1],t[r+2]=Sr[2],t[r+3]=Sr[3]}function x0(e,t){return Sr[0]=e[t],Sr[1]=e[t+1],Sr[2]=e[t+2],Sr[3]=e[t+3],ec[0]}var rc=new Float64Array([-0]),te=new Uint8Array(rc.buffer);function b0(e,t,r){rc[0]=e,t[r]=te[0],t[r+1]=te[1],t[r+2]=te[2],t[r+3]=te[3],t[r+4]=te[4],t[r+5]=te[5],t[r+6]=te[6],t[r+7]=te[7]}function v0(e,t){return te[0]=e[t],te[1]=e[t+1],te[2]=e[t+2],te[3]=e[t+3],te[4]=e[t+4],te[5]=e[t+5],te[6]=e[t+6],te[7]=e[t+7],rc[0]}var K1=BigInt(Number.MAX_SAFE_INTEGER),V1=BigInt(Number.MIN_SAFE_INTEGER),ue=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Hr;if(t<K1&&t>V1)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,i=t-(n<<32n);return r&&(n=~n|0n,i=~i|0n,++i>E0&&(i=0n,++n>E0&&(n=0n))),new e(Number(i),Number(n))}static fromNumber(t){if(t===0)return Hr;let r=t<0;r&&(t=-t);let n=t>>>0,i=(t-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new e(n,i)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Hr}},Hr=new ue(0,0);Hr.toBigInt=function(){return 0n};Hr.zzEncode=Hr.zzDecode=function(){return this};Hr.length=function(){return 1};var E0=4294967296n;function w0(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function S0(e,t,r){if(r-t<1)return"";let i,o=[],s=0,a;for(;t<r;)a=e[t++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function nc(e,t,r){let n=r,i,o;for(let s=0;s<e.length;++s)i=e.charCodeAt(s),i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=i&63|128):(i&64512)===55296&&((o=e.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=i&63|128);return r-n}function Le(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ao(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var ic=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Le(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Le(this,4);return Ao(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Le(this,4);return Ao(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Le(this,4);let t=x0(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Le(this,4);let t=v0(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Le(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return S0(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Le(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Le(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new ue(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Le(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Le(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Le(this,8);let t=Ao(this.buf,this.pos+=4),r=Ao(this.buf,this.pos+=4);return new ue(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function oc(e){return new ic(e instanceof Uint8Array?e:e.subarray())}function Yt(e,t){let r=oc(e);return t.decode(r)}function sc(e){let t=e??8192,r=t>>>1,n,i=t;return function(s){if(s<1||s>r)return jt(s);i+s>t&&(n=jt(t),i=0);let a=n.subarray(i,i+=s);return i&7&&(i=(i|7)+1),a}}var Gr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function ac(){}var uc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},q1=sc();function z1(e){return globalThis.Buffer!=null?jt(e):q1(e)}var mi=class{len;head;tail;states;constructor(){this.len=0,this.head=new Gr(ac,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new Gr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new lc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(di,10,ue.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=ue.fromBigInt(t);return this._push(di,r.length(),r)}uint64Number(t){let r=ue.fromNumber(t);return this._push(di,r.length(),r)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=ue.fromBigInt(t).zzEncode();return this._push(di,r.length(),r)}sint64Number(t){let r=ue.fromNumber(t).zzEncode();return this._push(di,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(cc,1,t?1:0)}fixed32(t){return this._push(pi,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=ue.fromBigInt(t);return this._push(pi,4,r.lo)._push(pi,4,r.hi)}fixed64Number(t){let r=ue.fromNumber(t);return this._push(pi,4,r.lo)._push(pi,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(y0,4,t)}double(t){return this._push(b0,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(cc,1,0):this.uint32(r)._push(H1,r,t)}string(t){let r=w0(t);return r!==0?this.uint32(r)._push(nc,r,t):this._push(cc,1,0)}fork(){return this.states=new uc(this),this.head=this.tail=new Gr(ac,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Gr(ac,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=z1(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function cc(e,t,r){t[r]=e&255}function $1(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var lc=class extends Gr{next;constructor(t,r){super($1,t,r),this.next=void 0}};function di(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function pi(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function H1(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(mi.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(G1,t,e),this},mi.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Y1,t,e),this});function G1(e,t,r){t.set(e,r)}function Y1(e,t,r){e.length<40?nc(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(Y(e),r)}function fc(){return new mi}function Wt(e,t){let r=fc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Bn;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(Bn||(Bn={}));function Io(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function hc(e){function t(i){if(e[i.toString()]==null)throw new Error("Invalid enum value");return e[i]}let r=function(o,s){let a=t(o);s.int32(a)},n=function(o){let s=o.int32();return t(s)};return Io("enum",Bn.VARINT,r,n)}function Qt(e,t){return Io("message",Bn.LENGTH_DELIMITED,e,t)}var bt;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"})(bt||(bt={}));var dc;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"})(dc||(dc={}));(function(e){e.codec=()=>hc(dc)})(bt||(bt={}));var ze;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),bt.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=bt.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})(ze||(ze={}));var $e;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),bt.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=bt.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})($e||($e={}));var gi=class{_key;constructor(t){this._key=Ln(t,Rn)}verify(t,r){return p0(this._key,r,t)}marshal(){return this._key}get bytes(){return ze.encode({Type:bt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Gt.digest(this.bytes);return ve(t)?t.then(({bytes:r})=>r):t.bytes}},Yr=class{_key;_publicKey;constructor(t,r){this._key=Ln(t,ir),this._publicKey=Ln(r,Rn)}sign(t){return d0(this._key,t)}get public(){return new gi(this._publicKey)}marshal(){return this._key}get bytes(){return $e.encode({Type:bt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Gt.digest(this.bytes),r;return ve(t)?{bytes:r}=await t:r=t.bytes,r}async id(){let t=yr.digest(this.public.bytes);return vt.encode(t.bytes).substring(1)}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Tn(this.bytes,t);throw new A(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function W1(e){if(e.length>ir){e=Ln(e,ir+Rn);let n=e.subarray(0,ir),i=e.subarray(ir,e.length);return new Yr(n,i)}e=Ln(e,ir);let t=e.subarray(0,ir),r=e.subarray(Rn);return new Yr(t,r)}function Q1(e){return e=Ln(e,Rn),new gi(e)}async function X1(){let{privateKey:e,publicKey:t}=f0();return new Yr(e,t)}async function I0(e){let{privateKey:t,publicKey:r}=h0(e);return new Yr(t,r)}function Ln(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new A(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}var Z1={"P-256":256,"P-384":384,"P-521":521},J1=Object.keys(Z1),HS=J1.join(" / ");var bc={};Ut(bc,{MAX_KEY_SIZE:()=>vi,RsaPrivateKey:()=>Dn,RsaPublicKey:()=>bi,fromJwk:()=>ux,generateKeyPair:()=>lx,unmarshalRsaPrivateKey:()=>ax,unmarshalRsaPublicKey:()=>cx});var xi=St(ft(),1);var TA=St(B0(),1);function Co(e){if(isNaN(e)||e<=0)throw new A("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return In(e)}var fA=St(io(),1),yc=St(ft(),1);function L0(e,t){return t.map(r=>de(e[r]))}function D0(e){return yc.default.pki.setRsaPrivateKey(...L0(e,["n","e","d","p","q","dp","dq","qi"]))}function P0(e){return yc.default.pki.setRsaPublicKey(...L0(e,["n","e"]))}var Qr={};Ut(Qr,{jwkToPkcs1:()=>rx,jwkToPkix:()=>ix,pkcs1ToJwk:()=>ex,pkixToJwk:()=>nx});var pA=St(ii(),1),mA=St(io(),1);var or=St(ft(),1);function ex(e){let t=or.default.asn1.fromDer(it(e,"ascii")),r=or.default.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:Ce(r.n),e:Ce(r.e),d:Ce(r.d),p:Ce(r.p),q:Ce(r.q),dp:Ce(r.dP),dq:Ce(r.dQ),qi:Ce(r.qInv),alg:"RS256"}}function rx(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new A("JWK was missing components","ERR_INVALID_PARAMETERS");let t=or.default.pki.privateKeyToAsn1({n:de(e.n),e:de(e.e),d:de(e.d),p:de(e.p),q:de(e.q),dP:de(e.dp),dQ:de(e.dq),qInv:de(e.qi)});return Y(or.default.asn1.toDer(t).getBytes(),"ascii")}function nx(e){let t=or.default.asn1.fromDer(it(e,"ascii")),r=or.default.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:Ce(r.n),e:Ce(r.e)}}function ix(e){if(e.n==null||e.e==null)throw new A("JWK was missing components","ERR_INVALID_PARAMETERS");let t=or.default.pki.publicKeyToAsn1({n:de(e.n),e:de(e.e)});return Y(or.default.asn1.toDer(t).getBytes(),"ascii")}async function N0(e){let t=await ce.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await M0(t);return{privateKey:r[0],publicKey:r[1]}}async function xc(e){let r=[await ce.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await ox(e)],n=await M0({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function O0(e,t){let r=await ce.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ce.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function k0(e,t,r){let n=await ce.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ce.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function M0(e){if(e.privateKey==null||e.publicKey==null)throw new A("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([ce.get().subtle.exportKey("jwk",e.privateKey),ce.get().subtle.exportKey("jwk",e.publicKey)])}async function ox(e){return ce.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function U0(e,t,r,n){let i=t?P0(e):D0(e),o=it(r instanceof Uint8Array?r:r.subarray(),"ascii"),s=n(o,i);return Y(s,"ascii")}function F0(e,t){return U0(e,!0,t,(r,n)=>n.encrypt(r))}function K0(e,t){return U0(e,!1,t,(r,n)=>n.decrypt(r))}function Ro(e){if(e.kty!=="RSA")throw new A("invalid key type","ERR_INVALID_KEY_TYPE");if(e.n==null)throw new A("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Y(e.n,"base64url").length*8}var vi=8192,bi=class{_key;constructor(t){this._key=t}verify(t,r){return k0(this._key,r,t)}marshal(){return Qr.jwkToPkix(this._key)}get bytes(){return ze.encode({Type:bt.RSA,Data:this.marshal()}).subarray()}encrypt(t){return F0(this._key,t)}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Gt.digest(this.bytes);return ve(t)?t.then(({bytes:r})=>r):t.bytes}},Dn=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r}genSecret(){return Co(16)}sign(t){return O0(this._key,t)}get public(){if(this._publicKey==null)throw new A("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new bi(this._publicKey)}decrypt(t){return K0(this._key,t)}marshal(){return Qr.jwkToPkcs1(this._key)}get bytes(){return $e.encode({Type:bt.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Gt.digest(this.bytes);return ve(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return it(t,"base58btc")}async export(t,r="pkcs-8"){if(r==="pkcs-8"){let n=new xi.default.util.ByteBuffer(this.marshal()),i=xi.default.asn1.fromDer(n),o=xi.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return xi.default.pki.encryptRsaPrivateKey(o,t,s)}else{if(r==="libp2p-key")return Tn(this.bytes,t);throw new A(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function ax(e){let t=Qr.pkcs1ToJwk(e);if(Ro(t)>vi)throw new A("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await xc(t);return new Dn(r.privateKey,r.publicKey)}function cx(e){let t=Qr.pkixToJwk(e);if(Ro(t)>vi)throw new A("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new bi(t)}async function ux(e){if(Ro(e)>vi)throw new A("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await xc(e);return new Dn(t.privateKey,t.publicKey)}async function lx(e){if(e>vi)throw new A("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await N0(e);return new Dn(t.privateKey,t.publicKey)}var Ic={};Ut(Ic,{Secp256k1PrivateKey:()=>wi,Secp256k1PublicKey:()=>Ei,generateKeyPair:()=>Ix,unmarshalSecp256k1PrivateKey:()=>Sx,unmarshalSecp256k1PublicKey:()=>Ax});var fx=(e,t,r)=>e&t^~e&r,hx=(e,t,r)=>e&t^e&r^t&r,dx=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]),Ar=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ir=new Uint32Array(64),vc=class extends _n{constructor(){super(64,32,8,!1),this.A=Ar[0]|0,this.B=Ar[1]|0,this.C=Ar[2]|0,this.D=Ar[3]|0,this.E=Ar[4]|0,this.F=Ar[5]|0,this.G=Ar[6]|0,this.H=Ar[7]|0}get(){let{A:t,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[t,r,n,i,o,s,a,c]}set(t,r,n,i,o,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Ir[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let d=Ir[f-15],p=Ir[f-2],h=Re(d,7)^Re(d,18)^d>>>3,m=Re(p,17)^Re(p,19)^p>>>10;Ir[f]=m+Ir[f-7]+h+Ir[f-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Re(a,6)^Re(a,11)^Re(a,25),p=l+d+fx(a,c,u)+dx[f]+Ir[f]|0,m=(Re(n,2)^Re(n,13)^Re(n,22))+hx(n,i,o)|0;l=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+m|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+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,o,s,a,c,u,l)}roundClean(){Ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var V0=po(()=>new vc);function px(e){let t=hi(e);qe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:mx,hexToBytes:gx}=yo,Xr={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){let{Err:t}=Xr;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");let r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:mx(n),l:e.subarray(r+2)}},toSig(e){let{Err:t}=Xr,r=typeof e=="string"?gx(e):e;if(!Te(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:i,l:o}=Xr._parseInt(r.subarray(2)),{d:s,l:a}=Xr._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(e){let t=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=t(r(e.s)),i=t(r(e.r)),o=n.length/2,s=i.length/2,a=r(o),c=r(s);return`30${r(s+o+4)}02${c}${i}02${a}${n}`}},sr=BigInt(0),Ee=BigInt(1),FA=BigInt(2),q0=BigInt(3),KA=BigInt(4);function yx(e){let t=px(e),{Fp:r}=t,n=t.toBytes||((h,m,g)=>{let y=m.toAffine();return rr(Uint8Array.from([4]),r.toBytes(y.x),r.toBytes(y.y))}),i=t.fromBytes||(h=>{let m=h.subarray(1),g=r.fromBytes(m.subarray(0,r.BYTES)),y=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:g,y}});function o(h){let{a:m,b:g}=t,y=r.sqr(h),x=r.mul(y,h);return r.add(r.add(x,r.mul(h,m)),g)}if(!r.eql(r.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function s(h){return typeof h=="bigint"&&sr<h&&h<t.n}function a(h){if(!s(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:m,nByteLength:g,wrapPrivateKey:y,n:x}=t;if(m&&typeof h!="bigint"){if(Te(h)&&(h=tr(h)),typeof h!="string"||!m.includes(h.length))throw new Error("Invalid key");h=h.padStart(g*2,"0")}let b;try{b=typeof h=="bigint"?h:er(It("private key",h,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof h}`)}return y&&(b=ht(b,x)),a(b),b}let u=new Map;function l(h){if(!(h instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(m,g,y){if(this.px=m,this.py=g,this.pz=y,m==null||!r.isValid(m))throw new Error("x required");if(g==null||!r.isValid(g))throw new Error("y required");if(y==null||!r.isValid(y))throw new Error("z required")}static fromAffine(m){let{x:g,y}=m||{};if(!m||!r.isValid(g)||!r.isValid(y))throw new Error("invalid affine point");if(m instanceof f)throw new Error("projective point not allowed");let x=b=>r.eql(b,r.ZERO);return x(g)&&x(y)?f.ZERO:new f(g,y,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let g=r.invertBatch(m.map(y=>y.pz));return m.map((y,x)=>y.toAffine(g[x])).map(f.fromAffine)}static fromHex(m){let g=f.fromAffine(i(It("pointHex",m)));return g.assertValidity(),g}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y:g}=this.toAffine();if(!r.isValid(m)||!r.isValid(g))throw new Error("bad point: x or y not FE");let y=r.sqr(g),x=o(m);if(!r.eql(y,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){l(m);let{px:g,py:y,pz:x}=this,{px:b,py:_,pz:w}=m,S=r.eql(r.mul(g,w),r.mul(b,x)),D=r.eql(r.mul(y,w),r.mul(_,x));return S&&D}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:g}=t,y=r.mul(g,q0),{px:x,py:b,pz:_}=this,w=r.ZERO,S=r.ZERO,D=r.ZERO,P=r.mul(x,x),$=r.mul(b,b),H=r.mul(_,_),q=r.mul(x,b);return q=r.add(q,q),D=r.mul(x,_),D=r.add(D,D),w=r.mul(m,D),S=r.mul(y,H),S=r.add(w,S),w=r.sub($,S),S=r.add($,S),S=r.mul(w,S),w=r.mul(q,w),D=r.mul(y,D),H=r.mul(m,H),q=r.sub(P,H),q=r.mul(m,q),q=r.add(q,D),D=r.add(P,P),P=r.add(D,P),P=r.add(P,H),P=r.mul(P,q),S=r.add(S,P),H=r.mul(b,_),H=r.add(H,H),P=r.mul(H,q),w=r.sub(w,P),D=r.mul(H,$),D=r.add(D,D),D=r.add(D,D),new f(w,S,D)}add(m){l(m);let{px:g,py:y,pz:x}=this,{px:b,py:_,pz:w}=m,S=r.ZERO,D=r.ZERO,P=r.ZERO,$=t.a,H=r.mul(t.b,q0),q=r.mul(g,b),J=r.mul(y,_),lt=r.mul(x,w),zt=r.add(g,y),T=r.add(b,_);zt=r.mul(zt,T),T=r.add(q,J),zt=r.sub(zt,T),T=r.add(g,x);let O=r.add(b,w);return T=r.mul(T,O),O=r.add(q,lt),T=r.sub(T,O),O=r.add(y,x),S=r.add(_,w),O=r.mul(O,S),S=r.add(J,lt),O=r.sub(O,S),P=r.mul($,T),S=r.mul(H,lt),P=r.add(S,P),S=r.sub(J,P),P=r.add(J,P),D=r.mul(S,P),J=r.add(q,q),J=r.add(J,q),lt=r.mul($,lt),T=r.mul(H,T),J=r.add(J,lt),lt=r.sub(q,lt),lt=r.mul($,lt),T=r.add(T,lt),q=r.mul(J,T),D=r.add(D,q),q=r.mul(O,T),S=r.mul(zt,S),S=r.sub(S,q),q=r.mul(zt,J),P=r.mul(O,P),P=r.add(P,q),new f(S,D,P)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return p.wNAFCached(this,u,m,g=>{let y=r.invertBatch(g.map(x=>x.pz));return g.map((x,b)=>x.toAffine(y[b])).map(f.fromAffine)})}multiplyUnsafe(m){let g=f.ZERO;if(m===sr)return g;if(a(m),m===Ee)return this;let{endo:y}=t;if(!y)return p.unsafeLadder(this,m);let{k1neg:x,k1:b,k2neg:_,k2:w}=y.splitScalar(m),S=g,D=g,P=this;for(;b>sr||w>sr;)b&Ee&&(S=S.add(P)),w&Ee&&(D=D.add(P)),P=P.double(),b>>=Ee,w>>=Ee;return x&&(S=S.negate()),_&&(D=D.negate()),D=new f(r.mul(D.px,y.beta),D.py,D.pz),S.add(D)}multiply(m){a(m);let g=m,y,x,{endo:b}=t;if(b){let{k1neg:_,k1:w,k2neg:S,k2:D}=b.splitScalar(g),{p:P,f:$}=this.wNAF(w),{p:H,f:q}=this.wNAF(D);P=p.constTimeNegate(_,P),H=p.constTimeNegate(S,H),H=new f(r.mul(H.px,b.beta),H.py,H.pz),y=P.add(H),x=$.add(q)}else{let{p:_,f:w}=this.wNAF(g);y=_,x=w}return f.normalizeZ([y,x])[0]}multiplyAndAddUnsafe(m,g,y){let x=f.BASE,b=(w,S)=>S===sr||S===Ee||!w.equals(x)?w.multiplyUnsafe(S):w.multiply(S),_=b(this,g).add(b(m,y));return _.is0()?void 0:_}toAffine(m){let{px:g,py:y,pz:x}=this,b=this.is0();m==null&&(m=b?r.ONE:r.inv(x));let _=r.mul(g,m),w=r.mul(y,m),S=r.mul(x,m);if(b)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:_,y:w}}isTorsionFree(){let{h:m,isTorsionFree:g}=t;if(m===Ee)return!0;if(g)return g(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:g}=t;return m===Ee?this:g?g(f,this):this.multiplyUnsafe(t.h)}toRawBytes(m=!0){return this.assertValidity(),n(f,this,m)}toHex(m=!0){return tr(this.toRawBytes(m))}}f.BASE=new f(t.Gx,t.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let d=t.nBitLength,p=vo(f,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function xx(e){let t=hi(e);return qe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function z0(e){let t=xx(e),{Fp:r,n}=t,i=r.BYTES+1,o=2*r.BYTES+1;function s(T){return sr<T&&T<r.ORDER}function a(T){return ht(T,n)}function c(T){return xo(T,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:f,isWithinCurveOrder:d}=yx({...t,toBytes(T,O,L){let N=O.toAffine(),C=r.toBytes(N.x),U=rr;return L?U(Uint8Array.from([O.hasEvenY()?2:3]),C):U(Uint8Array.from([4]),C,r.toBytes(N.y))},fromBytes(T){let O=T.length,L=T[0],N=T.subarray(1);if(O===i&&(L===2||L===3)){let C=er(N);if(!s(C))throw new Error("Point is not on curve");let U=f(C),K=r.sqrt(U),z=(K&Ee)===Ee;return(L&1)===1!==z&&(K=r.neg(K)),{x:C,y:K}}else if(O===o&&L===4){let C=r.fromBytes(N.subarray(0,r.BYTES)),U=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:C,y:U}}else throw new Error(`Point of length ${O} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=T=>tr(wr(T,t.nByteLength));function h(T){let O=n>>Ee;return T>O}function m(T){return h(T)?a(-T):T}let g=(T,O,L)=>er(T.slice(O,L));class y{constructor(O,L,N){this.r=O,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(O){let L=t.nByteLength;return O=It("compactSignature",O,L*2),new y(g(O,0,L),g(O,L,2*L))}static fromDER(O){let{r:L,s:N}=Xr.toSig(It("DER",O));return new y(L,N)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(O){return new y(this.r,this.s,O)}recoverPublicKey(O){let{r:L,s:N,recovery:C}=this,U=D(It("msgHash",O));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let K=C===2||C===3?L+t.n:L;if(K>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=C&1?"03":"02",X=u.fromHex(z+p(K)),j=c(K),ct=a(-U*j),et=a(N*j),ot=u.BASE.multiplyAndAddUnsafe(X,ct,et);if(!ot)throw new Error("point at infinify");return ot.assertValidity(),ot}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return qr(this.toDERHex())}toDERHex(){return Xr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let x={isValidPrivateKey(T){try{return l(T),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let T=Wa(t.n);return s0(t.randomBytes(T),t.n)},precompute(T=8,O=u.BASE){return O._setWindowSize(T),O.multiply(BigInt(3)),O}};function b(T,O=!0){return u.fromPrivateKey(T).toRawBytes(O)}function _(T){let O=Te(T),L=typeof T=="string",N=(O||L)&&T.length;return O?N===i||N===o:L?N===2*i||N===2*o:T instanceof u}function w(T,O,L=!0){if(_(T))throw new Error("first arg must be private key");if(!_(O))throw new Error("second arg must be public key");return u.fromHex(O).multiply(l(T)).toRawBytes(L)}let S=t.bits2int||function(T){let O=er(T),L=T.length*8-t.nBitLength;return L>0?O>>BigInt(L):O},D=t.bits2int_modN||function(T){return a(S(T))},P=fi(t.nBitLength);function $(T){if(typeof T!="bigint")throw new Error("bigint expected");if(!(sr<=T&&T<P))throw new Error(`bigint expected < 2^${t.nBitLength}`);return wr(T,t.nByteLength)}function H(T,O,L=q){if(["recovered","canonical"].some(wt=>wt in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:C}=t,{lowS:U,prehash:K,extraEntropy:z}=L;U==null&&(U=!0),T=It("msgHash",T),K&&(T=It("prehashed msgHash",N(T)));let X=D(T),j=l(O),ct=[$(j),$(X)];if(z!=null){let wt=z===!0?C(r.BYTES):z;ct.push(It("extraEntropy",wt))}let et=rr(...ct),ot=X;function Bt(wt){let $t=S(wt);if(!d($t))return;let Ht=c($t),Ot=u.BASE.multiply($t).toAffine(),Jt=a(Ot.x);if(Jt===sr)return;let Ye=a(Ht*a(ot+Jt*j));if(Ye===sr)return;let Pr=(Ot.x===Jt?0:2)|Number(Ot.y&Ee),ti=Ye;return U&&h(Ye)&&(ti=m(Ye),Pr^=1),new y(Jt,ti,Pr)}return{seed:et,k2sig:Bt}}let q={lowS:t.lowS,prehash:!1},J={lowS:t.lowS,prehash:!1};function lt(T,O,L=q){let{seed:N,k2sig:C}=H(T,O,L),U=t;return $a(U.hash.outputLen,U.nByteLength,U.hmac)(N,C)}u.BASE._setWindowSize(8);function zt(T,O,L,N=J){let C=T;if(O=It("msgHash",O),L=It("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:U,prehash:K}=N,z,X;try{if(typeof C=="string"||Te(C))try{z=y.fromDER(C)}catch(Ot){if(!(Ot instanceof Xr.Err))throw Ot;z=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){let{r:Ot,s:Jt}=C;z=new y(Ot,Jt)}else throw new Error("PARSE");X=u.fromHex(L)}catch(Ot){if(Ot.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(U&&z.hasHighS())return!1;K&&(O=t.hash(O));let{r:j,s:ct}=z,et=D(O),ot=c(ct),Bt=a(et*ot),wt=a(j*ot),$t=u.BASE.multiplyAndAddUnsafe(X,Bt,wt)?.toAffine();return $t?a($t.x)===j:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:w,sign:lt,verify:zt,ProjectivePoint:u,Signature:y,utils:x}}var To=class extends An{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,Yf(t);let n=li(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(t){return Sn(this),this.iHash.update(t),this}digestInto(t){Sn(this),Ma(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ec=(e,t,r)=>new To(e,t).update(r).digest();Ec.create=(e,t)=>new To(e,t);function bx(e){return{hash:e,hmac:(t,...r)=>Ec(e,t,ho(...r)),randomBytes:In}}function $0(e,t){let r=n=>z0({...e,...bx(n)});return Object.freeze({...r(t),create:r})}var Y0=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),H0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),vx=BigInt(1),wc=BigInt(2),G0=(e,t)=>(e+t/wc)/t;function Ex(e){let t=Y0,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,f=xt(l,r,t)*l%t,d=xt(f,r,t)*l%t,p=xt(d,wc,t)*u%t,h=xt(p,i,t)*p%t,m=xt(h,o,t)*h%t,g=xt(m,a,t)*m%t,y=xt(g,c,t)*g%t,x=xt(y,a,t)*m%t,b=xt(x,r,t)*l%t,_=xt(b,s,t)*h%t,w=xt(_,n,t)*u%t,S=xt(w,wc,t);if(!Sc.eql(Sc.sqr(S),e))throw new Error("Cannot find square root");return S}var Sc=bo(Y0,void 0,void 0,{sqrt:Ex}),De=$0({a:BigInt(0),b:BigInt(7),Fp:Sc,n:H0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=H0,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-vx*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=G0(o*e,t),c=G0(-n*e,t),u=ht(e-a*r-c*i,t),l=ht(-a*n-c*o,t),f=u>s,d=l>s;if(f&&(u=t-u),d&&(l=t-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},V0),JA=BigInt(0);var jA=De.ProjectivePoint;function W0(){return De.utils.randomPrivateKey()}function Q0(e,t){let r=Gt.digest(t instanceof Uint8Array?t:t.subarray());if(ve(r))return r.then(({digest:n})=>De.sign(n,e).toDERRawBytes()).catch(n=>{throw new A(String(n),"ERR_INVALID_INPUT")});try{return De.sign(r.digest,e).toDERRawBytes()}catch(n){throw new A(String(n),"ERR_INVALID_INPUT")}}function X0(e,t,r){let n=Gt.digest(r instanceof Uint8Array?r:r.subarray());if(ve(n))return n.then(({digest:i})=>De.verify(t,i,e)).catch(i=>{throw new A(String(i),"ERR_INVALID_INPUT")});try{return De.verify(t,n.digest,e)}catch(i){throw new A(String(i),"ERR_INVALID_INPUT")}}function Z0(e){return De.ProjectivePoint.fromHex(e).toRawBytes(!0)}function J0(e){try{De.getPublicKey(e,!0)}catch(t){throw new A(String(t),"ERR_INVALID_PRIVATE_KEY")}}function Ac(e){try{De.ProjectivePoint.fromHex(e)}catch(t){throw new A(String(t),"ERR_INVALID_PUBLIC_KEY")}}function j0(e){try{return De.getPublicKey(e,!0)}catch(t){throw new A(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Ei=class{_key;constructor(t){Ac(t),this._key=t}verify(t,r){return X0(this._key,r,t)}marshal(){return Z0(this._key)}get bytes(){return ze.encode({Type:bt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Gt.digest(this.bytes),r;return ve(t)?{bytes:r}=await t:r=t.bytes,r}},wi=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r??j0(t),J0(this._key),Ac(this._publicKey)}sign(t){return Q0(this._key,t)}get public(){return new Ei(this._publicKey)}marshal(){return this._key}get bytes(){return $e.encode({Type:bt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Gt.digest(this.bytes);return ve(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return it(t,"base58btc")}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Tn(this.bytes,t);throw new A(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Sx(e){return new wi(e)}function Ax(e){return new Ei(e)}async function Ix(){let e=W0();return new wi(e)}var _r={rsa:bc,ed25519:pc,secp256k1:Ic};function _c(e){let t=Object.keys(_r).join(" / ");return new A(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Cc(e){if(e=e.toLowerCase(),e==="rsa"||e==="ed25519"||e==="secp256k1")return _r[e];throw _c(e)}async function th(e,t){return Cc(e).generateKeyPair(t??2048)}function Si(e){let t=ze.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case bt.RSA:return _r.rsa.unmarshalRsaPublicKey(r);case bt.Ed25519:return _r.ed25519.unmarshalEd25519PublicKey(r);case bt.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw _c(t.Type??"unknown")}}function eh(e,t){return t=(t??"rsa").toLowerCase(),Cc(t),e.bytes}async function Rc(e){let t=$e.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case bt.RSA:return _r.rsa.unmarshalRsaPrivateKey(r);case bt.Ed25519:return _r.ed25519.unmarshalEd25519PrivateKey(r);case bt.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw _c(t.Type??"RSA")}}function rh(e,t){return t=(t??"rsa").toLowerCase(),Cc(t),e.bytes}var ge=St(Bc(),1);ge.default.formatters.b=e=>e==null?"undefined":vt.baseEncode(e);ge.default.formatters.t=e=>e==null?"undefined":he.baseEncode(e);ge.default.formatters.m=e=>e==null?"undefined":bn.baseEncode(e);ge.default.formatters.p=e=>e==null?"undefined":e.toString();ge.default.formatters.c=e=>e==null?"undefined":e.toString();ge.default.formatters.k=e=>e==null?"undefined":e.toString();ge.default.formatters.a=e=>e==null?"undefined":e.toString();function Fx(e){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}function Do(){return{forComponent(e){return Kx(e)}}}function Kx(e){let t=Fx(`${e}:trace`);return ge.default.enabled(`${e}:trace`)&&ge.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(t=(0,ge.default)(`${e}:trace`)),Object.assign((0,ge.default)(e),{error:(0,ge.default)(`${e}:error`),trace:t})}var Vx=Symbol.for("nodejs.util.inspect.custom"),sh=Object.values(xr).map(e=>e.decoder).reduce((e,t)=>e.or(t),xr.identity.decoder),ah=114,Lc=36,Dc=37,Ai=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[fa]=!0;toString(){return this.string==null&&(this.string=vt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return _e.createV1(ah,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return Dt(t).equals(this);if(t?.multihash?.bytes!=null)return Et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[Vx](){return`PeerId(${this.toString()})`}},Jr=class extends Ai{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},jr=class extends Ai{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},tn=class extends Ai{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function ch(e){if(e.type==="RSA")return new Jr(e);if(e.type==="Ed25519")return new jr(e);if(e.type==="secp256k1")return new tn(e);throw new A("Not a PeerId","ERR_INVALID_PARAMETERS")}function Dt(e,t){if(t=t??sh,e.charAt(0)==="1"||e.charAt(0)==="Q"){let r=Kr(vt.decode(`z${e}`));return e.startsWith("12D")?new jr({multihash:r}):e.startsWith("16U")?new tn({multihash:r}):new Jr({multihash:r})}return kn(sh.decode(e))}function kn(e){try{let t=Kr(e);if(t.code===yr.code){if(t.digest.length===Lc)return new jr({multihash:t});if(t.digest.length===Dc)return new tn({multihash:t})}if(t.code===Gt.code)return new Jr({multihash:t})}catch{return qx(_e.decode(e))}throw new Error("Supplied PeerID CID is invalid")}function qx(e){if(e==null||e.multihash==null||e.version==null||e.version===1&&e.code!==ah)throw new Error("Supplied PeerID CID is invalid");let t=e.multihash;if(t.code===Gt.code)return new Jr({multihash:e.multihash});if(t.code===yr.code){if(t.digest.length===Lc)return new jr({multihash:e.multihash});if(t.digest.length===Dc)return new tn({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Po(e,t){return e.length===Lc?new jr({multihash:Ve(yr.code,e),privateKey:t}):e.length===Dc?new tn({multihash:Ve(yr.code,e),privateKey:t}):new Jr({multihash:await Gt.digest(e),publicKey:e,privateKey:t})}function en(e,t){let r={[Symbol.iterator]:()=>r,next:()=>{let n=e.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:t(i)}}};return r}var le=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[r,n]of t.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return en(this.map.entries(),t=>[Dt(t[0]),t[1]])}forEach(t){this.map.forEach((r,n)=>{t(r,Dt(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,r){this.map.set(t.toString(),r)}keys(){return en(this.map.keys(),t=>Dt(t))}values(){return this.map.values()}get size(){return this.map.size}};var we=class e{set;constructor(t){if(this.set=new Set,t!=null)for(let r of t)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return en(this.set.entries(),t=>{let r=Dt(t[0]);return[r,r]})}forEach(t){this.set.forEach(r=>{let n=Dt(r);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return en(this.set.values(),t=>Dt(t))}intersection(t){let r=new e;for(let n of t)this.has(n)&&r.add(n);return r}difference(t){let r=new e;for(let n of this)t.has(n)||r.add(n);return r}union(t){let r=new e;for(let n of t)r.add(n);for(let n of this)r.add(n);return r}};var Pc;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.id!=null&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})(Pc||(Pc={}));var uh=async()=>{let e=await th("Ed25519"),t=await $x(e);if(t.type==="Ed25519")return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function $x(e){return Po(eh(e.public),rh(e))}var Hx=Math.pow(2,7),Gx=Math.pow(2,14),Yx=Math.pow(2,21),Nc=Math.pow(2,28),Oc=Math.pow(2,35),kc=Math.pow(2,42),Mc=Math.pow(2,49),at=128,ee=127;function re(e){if(e<Hx)return 1;if(e<Gx)return 2;if(e<Yx)return 3;if(e<Nc)return 4;if(e<Oc)return 5;if(e<kc)return 6;if(e<Mc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wx(e,t,r=0){switch(re(e)){case 8:t[r++]=e&255|at,e/=128;case 7:t[r++]=e&255|at,e/=128;case 6:t[r++]=e&255|at,e/=128;case 5:t[r++]=e&255|at,e/=128;case 4:t[r++]=e&255|at,e>>>=7;case 3:t[r++]=e&255|at,e>>>=7;case 2:t[r++]=e&255|at,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Qx(e,t,r=0){switch(re(e)){case 8:t.set(r++,e&255|at),e/=128;case 7:t.set(r++,e&255|at),e/=128;case 6:t.set(r++,e&255|at),e/=128;case 5:t.set(r++,e&255|at),e/=128;case 4:t.set(r++,e&255|at),e>>>=7;case 3:t.set(r++,e&255|at),e>>>=7;case 2:t.set(r++,e&255|at),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Xx(e,t){let r=e[t],n=0;if(n+=r&ee,r<at||(r=e[t+1],n+=(r&ee)<<7,r<at)||(r=e[t+2],n+=(r&ee)<<14,r<at)||(r=e[t+3],n+=(r&ee)<<21,r<at)||(r=e[t+4],n+=(r&ee)*Nc,r<at)||(r=e[t+5],n+=(r&ee)*Oc,r<at)||(r=e[t+6],n+=(r&ee)*kc,r<at)||(r=e[t+7],n+=(r&ee)*Mc,r<at))return n;throw new RangeError("Could not decode varint")}function Zx(e,t){let r=e.get(t),n=0;if(n+=r&ee,r<at||(r=e.get(t+1),n+=(r&ee)<<7,r<at)||(r=e.get(t+2),n+=(r&ee)<<14,r<at)||(r=e.get(t+3),n+=(r&ee)<<21,r<at)||(r=e.get(t+4),n+=(r&ee)*Nc,r<at)||(r=e.get(t+5),n+=(r&ee)*Oc,r<at)||(r=e.get(t+6),n+=(r&ee)*kc,r<at)||(r=e.get(t+7),n+=(r&ee)*Mc,r<at))return n;throw new RangeError("Could not decode varint")}function fe(e,t,r=0){return t==null&&(t=jt(re(e))),t instanceof Uint8Array?Wx(e,t,r):Qx(e,t,r)}function Pe(e,t=0){return e instanceof Uint8Array?Xx(e,t):Zx(e,t)}var fh=Symbol.for("@achingbrain/uint8arraylist");function lh(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let i=r+n.byteLength;if(t<i)return{buf:n,index:t-r};r=i}throw new RangeError("index is out of bounds")}function No(e){return!!e?.[fh]}var qt=class e{bufs;length;[fh]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(No(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(No(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=lh(this.bufs,t);return r.buf[r.index]}set(t,r){let n=lh(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(No(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:i}=this._subList(t,r);return Ct(n,i)}subarray(t,r){let{bufs:n,length:i}=this._subList(t,r);return n.length===1?n[0]:Ct(n,i)}sublist(t,r){let{bufs:n,length:i}=this._subList(t,r),o=new e;return o.length=i,o.bufs=[...n],o}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===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,t>=c)continue;let u=t>=a&&t<c,l=r>a&&r<=c;if(u&&l){if(t===a&&r===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(r-t)));break}if(u){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(l){if(r===c){n.push(s);break}n.push(s.subarray(0,r-a));break}n.push(s)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!No(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let p=this.get(f+d);if(n[d]!==p){l=Math.max(1,d-a[p]);break}}if(l===0)return f}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=jt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let i=Je(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let i=Je(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let i=Je(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=jt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let i=Je(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let i=Je(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let i=Je(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let i=Je(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let i=Je(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Et(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};var hh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Ii;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.publicKey!=null&&r.publicKey.byteLength>0&&(n.uint32(10),n.bytes(r.publicKey)),r.payloadType!=null&&r.payloadType.byteLength>0&&(n.uint32(18),n.bytes(r.payloadType)),r.payload!=null&&r.payload.byteLength>0&&(n.uint32(26),n.bytes(r.payload)),r.signature!=null&&r.signature.byteLength>0&&(n.uint32(42),n.bytes(r.signature)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})(Ii||(Ii={}));var Mn=class e{static createFromProtobuf=async t=>{let r=Ii.decode(t),n=await Po(r.publicKey);return new e({peerId:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(t,r)=>{if(r.privateKey==null)throw new Error("Missing private key");let n=t.domain,i=t.codec,o=t.marshal(),s=dh(n,i,o),c=await(await Rc(r.privateKey)).sign(s.subarray());return new e({peerId:r,payloadType:i,payload:o,signature:c})};static openAndCertify=async(t,r)=>{let n=await e.createFromProtobuf(t);if(!await n.validate(r))throw new A("envelope signature is not valid for the given domain",hh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(t){let{peerId:r,payloadType:n,payload:i,signature:o}=t;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Ii.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return Et(this.marshal(),t.marshal())}async validate(t){let r=dh(t,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Si(this.peerId.publicKey).verify(r.subarray(),this.signature)}},dh=(e,t,r)=>{let n=Y(e),i=fe(n.byteLength),o=fe(t.length),s=fe(r.length);return new qt(i,n,o,t,s,r)};function ph(e,t){let r=(n,i)=>n.toString().localeCompare(i.toString());return e.length!==t.length?!1:(t.sort(r),e.sort(r).every((n,i)=>t[i].equals(n)))}var Oo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}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(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(o*=t,o+=l,o>u||(s+=1,r!==void 0&&s>r))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return r[i]=s[0],r[i+1]=s[1],r[i+2]=s[2],r[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];r[i]=o>>8,r[i+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=t(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=t(o.subarray(0,s));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var mh=45,Jx=15,Un=new Oo;function Uc(e){if(!(e.length>Jx))return Un.new(e).parseWith(()=>Un.readIPv4Addr())}function Fc(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>mh))return Un.new(e).parseWith(()=>Un.readIPv6Addr())}function ko(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>mh))return Un.new(e).parseWith(()=>Un.readIPAddr())}var QI=parseInt("0xFFFF",16),XI=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Mo(e){return!!Uc(e)}function Uo(e){return!!Fc(e)}function Fn(e){return!!ko(e)}var xh=Mo,n2=Uo,Kc=function(e){let t=0;if(e=e.toString().trim(),xh(e)){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(n=>{r[t++]=parseInt(n,10)&255}),r}if(n2(e)){let r=e.split(":",8),n;for(n=0;n<r.length;n++){let o=xh(r[n]),s;o&&(s=Kc(r[n]),r[n]=it(s.slice(0,2),"base16")),s!=null&&++n<8&&r.splice(n,0,it(s.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(t+16);for(n=0;n<r.length;n++){let o=parseInt(r[n],16);i[t++]=o>>8&255,i[t++]=o&255}return i}throw new Error("invalid ip address")},bh=function(e,t=0,r){t=~~t,r=r??e.length-t;let n=new DataView(e.buffer);if(r===4){let i=[];for(let o=0;o<r;o++)i.push(e[t+o]);return i.join(".")}if(r===16){let i=[];for(let o=0;o<r;o+=2)i.push(n.getUint16(t+o).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Kn={},Vc={},o2=[[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"]];o2.forEach(e=>{let t=s2(...e);Vc[t.code]=t,Kn[t.name]=t});function s2(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}function ut(e){if(typeof e=="number"){if(Vc[e]!=null)return Vc[e];throw new Error(`no protocol with code: ${e}`)}else if(typeof e=="string"){if(Kn[e]!=null)return Kn[e];throw new Error(`no protocol with name: ${e}`)}throw new Error(`invalid protocol id type: ${typeof e}`)}var P8=ut("ip4"),N8=ut("ip6"),O8=ut("ipcidr");function zc(e,t){switch(ut(e).code){case 4:case 41:return c2(t);case 42:return wh(t);case 6:case 273:case 33:case 132:return Ah(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return wh(t);case 421:return h2(t);case 444:return Sh(t);case 445:return Sh(t);case 466:return f2(t);default:return it(t,"base16")}}function $c(e,t){switch(ut(e).code){case 4:return vh(t);case 41:return vh(t);case 42:return Eh(t);case 6:case 273:case 33:case 132:return Hc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Eh(t);case 421:return u2(t);case 444:return d2(t);case 445:return p2(t);case 466:return l2(t);default:return Y(t,"base16")}}var qc=Object.values(xr).map(e=>e.decoder),a2=function(){let e=qc[0].or(qc[1]);return qc.slice(2).forEach(t=>e=e.or(t)),e}();function vh(e){if(!Fn(e))throw new Error("invalid ip address");return Kc(e)}function c2(e){let t=bh(e,0,e.length);if(t==null)throw new Error("ipBuff is required");if(!Fn(t))throw new Error("invalid ip address");return t}function Hc(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Ah(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Eh(e){let t=Y(e),r=Uint8Array.from(fe(t.length));return Ct([r,t],r.length+t.length)}function wh(e){let t=Pe(e);if(e=e.slice(re(t)),e.length!==t)throw new Error("inconsistent lengths");return it(e)}function u2(e){let t;e[0]==="Q"||e[0]==="1"?t=Kr(vt.decode(`z${e}`)).bytes:t=_e.parse(e).multihash.bytes;let r=Uint8Array.from(fe(t.length));return Ct([r,t],r.length+t.length)}function l2(e){let t=a2.decode(e),r=Uint8Array.from(fe(t.length));return Ct([r,t],r.length+t.length)}function f2(e){let t=Pe(e),r=e.slice(re(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+it(r,"base64url")}function h2(e){let t=Pe(e),r=e.slice(re(t));if(r.length!==t)throw new Error("inconsistent lengths");return it(r,"base58btc")}function d2(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=he.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Hc(n);return Ct([r,i],r.length+i.length)}function p2(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=he.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Hc(n);return Ct([r,i],r.length+i.length)}function Sh(e){let t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=it(t,"base32"),i=Ah(r);return`${n}:${i}`}function Ih(e){e=Gc(e);let t=[],r=[],n=null,i=e.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<i.length;o++){let s=i[o],a=ut(s);if(a.size===0){t.push([a.code]),r.push([a.code]);continue}if(o++,o>=i.length)throw Ch("invalid address: "+e);if(a.path===!0){n=Gc(i.slice(o).join("/")),t.push([a.code,$c(a.code,n)]),r.push([a.code,n]);break}let c=$c(a.code,i[o]);t.push([a.code,c]),r.push([a.code,zc(a.code,c)])}return{string:_h(r),bytes:Wc(t),tuples:t,stringTuples:r,path:n}}function Yc(e){let t=[],r=[],n=null,i=0;for(;i<e.length;){let o=Pe(e,i),s=re(o),a=ut(o),c=m2(a,e.slice(i+s));if(c===0){t.push([o]),r.push([o]),i+=s;continue}let u=e.slice(i+s,i+s+c);if(i+=c+s,i>e.length)throw Ch("Invalid address Uint8Array: "+it(e,"base16"));t.push([o,u]);let l=zc(o,u);if(r.push([o,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(e),string:_h(r),tuples:t,stringTuples:r,path:n}}function _h(e){let t=[];return e.map(r=>{let n=ut(r[0]);return t.push(n.name),r.length>1&&r[1]!=null&&t.push(r[1]),null}),Gc(t.join("/"))}function Wc(e){return Ct(e.map(t=>{let r=ut(t[0]),n=Uint8Array.from(fe(r.code));return t.length>1&&t[1]!=null&&(n=Ct([n,t[1]])),n}))}function m2(e,t){if(e.size>0)return e.size/8;if(e.size===0)return 0;{let r=Pe(t instanceof Uint8Array?t:Uint8Array.from(t));return r+re(r)}}function Gc(e){return"/"+e.trim().split("/").filter(t=>t).join("/")}function Ch(e){return new Error("Error parsing address: "+e)}var g2=Symbol.for("nodejs.util.inspect.custom"),Qc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),y2=[ut("dns").code,ut("dns4").code,ut("dns6").code,ut("dnsaddr").code],Fo=class e{bytes;#t;#e;#o;#a;[Qc]=!0;constructor(t){t==null&&(t="");let r;if(t instanceof Uint8Array)r=Yc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);r=Ih(t)}else if(Cr(t))r=Yc(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#t=r.string,this.#e=r.tuples,this.#o=r.stringTuples,this.#a=r.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,r,n,i,o="",s=ut("tcp"),a=ut("udp"),c=ut("ip4"),u=ut("ip6"),l=ut("dns6"),f=ut("ip6zone");for(let[p,h]of this.stringTuples())p===f.code&&(o=`%${h??""}`),y2.includes(p)&&(r=s.name,i=443,n=`${h??""}${o}`,t=p===l.code?6:4),(p===s.code||p===a.code)&&(r=ut(p).name,i=parseInt(h??"")),(p===c.code||p===u.code)&&(r=ut(p).name,n=`${h??""}${o}`,t=p===u.code?6:4);if(t==null||r==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:t,host:n,transport:r,port:i}}protos(){return this.#e.map(([t])=>Object.assign({},ut(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>ut(t).name)}tuples(){return this.#e}stringTuples(){return this.#o}encapsulate(t){return t=new e(t),new e(this.toString()+t.toString())}decapsulate(t){let r=t.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new e(n.slice(0,i))}decapsulateCode(t){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===t)return new e(Wc(r.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,i])=>{n===Kn.p2p.code&&t.push([n,i]),n===Kn["p2p-circuit"].code&&(t=[])});let r=t.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?it(vt.decode(`z${n}`),"base58btc"):it(_e.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return Et(this.bytes,t.bytes)}async resolve(t){let r=this.protos().find(o=>o.resolvable);if(r==null)return[this];let n=Ko.get(r.name);if(n==null)throw new A(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>new e(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let r=(t??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[g2](){return`Multiaddr(${this.#t})`}};var Ko=new Map;function Cr(e){return!!e?.[Qc]}function _t(e){return new Fo(e)}var Rh="libp2p-peer-record",Th=Uint8Array.from([3,1]);var _i;(function(e){let t;(function(n){let i;n.codec=()=>(i==null&&(i=Qt((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>Wt(o,n.codec()),n.decode=o=>Yt(o,n.codec())})(t=e.AddressInfo||(e.AddressInfo={}));let r;e.codec=()=>(r==null&&(r=Qt((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),e.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos<s;){let a=n.uint32();switch(a>>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(e.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),r),e.encode=n=>Wt(n,e.codec()),e.decode=n=>Yt(n,e.codec())})(_i||(_i={}));var nn=class e{static createFromProtobuf=t=>{let r=_i.decode(t),n=kn(r.peerId),i=(r.addresses??[]).map(s=>_t(s.multiaddr)),o=r.seq;return new e({peerId:n,multiaddrs:i,seqNumber:o})};static DOMAIN=Rh;static CODEC=Th;peerId;multiaddrs;seqNumber;domain=e.DOMAIN;codec=e.CODEC;marshaled;constructor(t){let{peerId:r,multiaddrs:n,seqNumber:i}=t;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=_i.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof e)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!ph(this.multiaddrs,t.multiaddrs))}};function x2(e){return e[Symbol.asyncIterator]!=null}function b2(e){if(x2(e))return(async()=>{let r=[];for await(let n of e)r.push(n);return r})();let t=[];for(let r of e)t.push(r);return t}var Ci=b2;var Zc=St(Lh(),1);var Ti=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Jc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Dh=e=>globalThis.DOMException===void 0?new Jc(e):new DOMException(e),Ph=e=>{let t=e.reason===void 0?Dh("This operation was aborted."):e.reason;return t instanceof Error?t:Dh(t)};function Bi(e,t){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=t,s,c=new Promise((u,l)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){let{signal:d}=t;d.aborted&&l(Ph(d)),d.addEventListener("abort",()=>{l(Ph(d))})}if(r===Number.POSITIVE_INFINITY){e.then(u,l);return}let f=new Ti;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){l(d)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${r} milliseconds`,l(f))},r),(async()=>{try{u(await e)}catch(d){l(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}function jc(e,t,r){let n=0,i=e.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(e[s],t)<=0?(n=++s,i-=o+1):i=o}return n}var Li=class{#t=[];enqueue(t,r){r={priority:0,...r};let n={priority:r.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=r.priority){this.#t.push(n);return}let i=jc(this.#t,n,(o,s)=>s.priority-o.priority);this.#t.splice(i,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this.#t.length}};var Vn=class extends Zc.default{#t;#e;#o=0;#a;#c;#p=0;#n;#u;#r;#m;#i=0;#l;#s;#g;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Li,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#s=t.autoStart===!1}get#b(){return this.#e||this.#o<this.#a}get#v(){return this.#i<this.#l}#E(){this.#i--,this.#f(),this.emit("next")}#w(){this.#x(),this.#y(),this.#u=void 0}get#S(){let t=Date.now();if(this.#n===void 0){let r=this.#p-t;if(r<0)this.#o=this.#t?this.#i:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#w()},r)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#s){let t=!this.#S;if(this.#b&&this.#v){let r=this.#r.dequeue();return r?(this.emit("active"),r(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#n!==void 0||(this.#n=setInterval(()=>{this.#x()},this.#c),this.#p=Date.now()+this.#c)}#x(){this.#o===0&&this.#i===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#t?this.#i:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#l}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#l=t,this.#h()}async#A(t){return new Promise((r,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,r={}){return r={timeout:this.timeout,throwOnTimeout:this.#g,...r},new Promise((n,i)=>{this.#r.enqueue(async()=>{this.#i++,this.#o++;try{r.signal?.throwIfAborted();let o=t({signal:r.signal});r.timeout&&(o=Bi(Promise.resolve(o),{milliseconds:r.timeout})),r.signal&&(o=Promise.race([o,this.#A(r.signal)]));let s=await o;n(s),this.emit("completed",s)}catch(o){if(o instanceof Ti&&!r.throwOnTimeout){n();return}i(o),this.emit("error",o)}finally{this.#E()}},r),this.emit("add"),this.#f()})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return this.#s?(this.#s=!1,this.#h(),this):this}pause(){this.#s=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#i===0&&this.#r.size===0||await this.#d("idle")}async#d(t,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(t,i),n())};this.on(t,i)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#i}get isPaused(){return this.#s}};var Rr={},qn=e=>{e.addEventListener("message",t=>{qn.dispatchEvent("message",e,t)}),e.port!=null&&e.port.addEventListener("message",t=>{qn.dispatchEvent("message",e,t)})};qn.addEventListener=(e,t)=>{Rr[e]==null&&(Rr[e]=[]),Rr[e].push(t)};qn.removeEventListener=(e,t)=>{Rr[e]!=null&&(Rr[e]=Rr[e].filter(r=>r===t))};qn.dispatchEvent=function(e,t,r){Rr[e]!=null&&Rr[e].forEach(n=>n(t,r))};var tu=qn;var eu="lock:worker:request-read",ru="lock:worker:release-read",nu="lock:master:grant-read",iu="lock:worker:request-write",ou="lock:worker:release-write",su="lock:master:grant-write";var Nh=(e=21)=>Math.random().toString().substring(2);var Oh=(e,t,r,n,i)=>(o,s)=>{if(s.data.type!==r)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)})}}}))},kh=(e,t,r,n)=>async()=>{let i=Nh();return globalThis.postMessage({type:t,identifier:i,name:e}),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===r&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:e})}))};globalThis.addEventListener("message",s)})},w2={singleProcess:!1},Mh=e=>{if(e=Object.assign({},w2,e),!!globalThis.document||e.singleProcess){let r=new EventTarget;return tu.addEventListener("message",Oh(r,"requestReadLock",eu,ru,nu)),tu.addEventListener("message",Oh(r,"requestWriteLock",iu,ou,su)),r}return{isWorker:!0,readLock:r=>kh(r,eu,nu,ru),writeLock:r=>kh(r,iu,su,ou)}};var on={},Tr;async function au(e,t){let r,n=new Promise(i=>{r=i});return e.add(async()=>Bi((async()=>{await new Promise(i=>{r(()=>{i()})})})(),{milliseconds:t.timeout})),n}var S2=(e,t)=>{if(Tr.isWorker===!0)return{readLock:Tr.readLock(e,t),writeLock:Tr.writeLock(e,t)};let r=new Vn({concurrency:1}),n;return{async readLock(){if(n!=null)return au(n,t);n=new Vn({concurrency:t.concurrency,autoStart:!1});let i=n,o=au(n,t);return r.add(async()=>{i.start(),await i.onIdle().then(()=>{n===i&&(n=null)})}),o},async writeLock(){return n=null,au(r,t)}}},A2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function cu(e){let t=Object.assign({},A2,e);return Tr==null&&(Tr=Mh(t),Tr.isWorker!==!0&&(Tr.addEventListener("requestReadLock",r=>{on[r.data.name]!=null&&on[r.data.name].readLock().then(async n=>r.data.handler().finally(()=>{n()}))}),Tr.addEventListener("requestWriteLock",async r=>{on[r.data.name]!=null&&on[r.data.name].writeLock().then(async n=>r.data.handler().finally(()=>{n()}))}))),on[t.name]==null&&(on[t.name]=S2(t.name,t)),on[t.name]}var Xt={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var zn;(function(e){let t;(function(i){let o;i.codec=()=>(o==null&&(o=Qt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=s.bytes();break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>Wt(s,i.codec()),i.decode=s=>Yt(s,i.codec())})(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={}));let r;(function(i){let o;i.codec=()=>(o==null&&(o=Qt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),zo.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=zo.codec().decode(s,s.uint32());break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>Wt(s,i.codec()),i.decode=s=>Yt(s,i.codec())})(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={}));let n;e.codec=()=>(n==null&&(n=Qt((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.addresses!=null)for(let a of i.addresses)o.uint32(10),qo.codec().encode(a,o);if(i.protocols!=null)for(let a of i.protocols)o.uint32(18),o.string(a);if(i.publicKey!=null&&(o.uint32(34),o.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())o.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())o.uint32(58),e.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.addresses.push(qo.codec().decode(i,i.uint32()));break;case 2:s.protocols.push(i.string());break;case 4:s.publicKey=i.bytes();break;case 5:s.peerRecordEnvelope=i.bytes();break;case 6:{let u=e.Peer$metadataEntry.codec().decode(i,i.uint32());s.metadata.set(u.key,u.value);break}case 7:{let u=e.Peer$tagsEntry.codec().decode(i,i.uint32());s.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return s})),n),e.encode=i=>Wt(i,e.codec()),e.decode=i=>Yt(i,e.codec())})(zn||(zn={}));var qo;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.multiaddr!=null&&r.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})(qo||(qo={}));var zo;(function(e){let t;e.codec=()=>(t==null&&(t=Qt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.value!=null&&r.value!==0&&(n.uint32(8),n.uint32(r.value)),r.expiry!=null&&(n.uint32(16),n.uint64(r.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={value:0},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.value=r.uint32();break;case 2:i.expiry=r.uint64();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Wt(r,e.codec()),e.decode=r=>Yt(r,e.codec())})(zo||(zo={}));function $n(e,t){let r=zn.decode(t);r.publicKey!=null&&e.publicKey==null&&(e=ch({...e,publicKey:e.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[o,s]of r.tags.entries())s.expiry!=null&&s.expiry<i||n.set(o,s);return{...r,id:e,addresses:r.addresses.map(({multiaddr:o,isCertified:s})=>({multiaddr:_t(o),isCertified:s??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}var ar="/",Uh=new TextEncoder().encode(ar),$o=Uh[0],sn=class e{_buf;constructor(t,r){if(typeof t=="string")this._buf=Y(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==$o)throw new Error("Invalid key")}toString(t="utf8"){return it(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new e(t.join(ar))}static random(){return new e(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new e(t):typeof t.uint8Array=="function"?new e(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Uh),this._buf[0]!==$o){let t=new Uint8Array(this._buf.byteLength+1);t.fill($o,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===$o;)this._buf=this._buf.subarray(0,-1)}less(t){let r=this.list(),n=t.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let o=r[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return r.length<n.length}reverse(){return e.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(ar).slice(1)}type(){return I2(this.baseNamespace())}name(){return _2(this.baseNamespace())}instance(t){return new e(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(ar)||(t+=ar),t+=this.type(),new e(t)}parent(){let t=this.list();return t.length===1?new e(ar):new e(t.slice(0,-1).join(ar))}child(t){return this.toString()===ar?t:t.toString()===ar?this:new e(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return e.withNamespaces([...this.namespaces(),...C2(t.map(r=>r.namespaces()))])}};function I2(e){let t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function _2(e){let t=e.split(":");return t[t.length-1]}function C2(e){return[].concat(...e)}var uu="/peers/";function Hn(e){if(!oo(e)||e.type==null)throw new A("Invalid PeerId",Xt.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new sn(`${uu}${t}`)}async function Fh(e,t,r){let n=new Map;for(let i of r){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=_t(i.multiaddr)),!Cr(i.multiaddr))throw new A("Multiaddr was invalid",Xt.ERR_INVALID_PARAMETERS);if(!await t(e,i.multiaddr))continue;let o=i.isCertified??!1,s=i.multiaddr.toString(),a=n.get(s);a!=null?i.isCertified=a.isCertified||o:n.set(s,{multiaddr:i.multiaddr,isCertified:o})}return[...n.values()].sort((i,o)=>i.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:i,multiaddr:o})=>({isCertified:i,multiaddr:o.bytes}))}async function Go(e,t,r,n){if(t==null)throw new A("Invalid PeerData",Xt.ERR_INVALID_PARAMETERS);if(t.publicKey!=null&&e.publicKey!=null&&!Et(t.publicKey,e.publicKey))throw new A("publicKey bytes do not match peer id publicKey bytes",Xt.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!e.equals(i.id))throw new A("peer id did not match existing peer id",Xt.ERR_INVALID_PARAMETERS);let o=i?.addresses??[],s=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(r==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(o=[],t.multiaddrs!=null&&o.push(...t.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),t.addresses!=null&&o.push(...t.addresses)),t.protocols!=null&&(s=new Set(t.protocols)),t.metadata!=null){let f=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Ho(f,{validate:Kh})}if(t.tags!=null){let f=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ho(f,{validate:Vh,map:qh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(r==="merge"){if(t.multiaddrs!=null&&o.push(...t.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),t.addresses!=null&&o.push(...t.addresses),t.protocols!=null&&(s=new Set([...s,...t.protocols])),t.metadata!=null){let f=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[d,p]of f)p==null?a.delete(d):a.set(d,p);a=Ho([...a.entries()],{validate:Kh})}if(t.tags!=null){let f=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),d=new Map(c);for(let[p,h]of f)h==null?d.delete(p):d.set(p,h);c=Ho([...d.entries()],{validate:Vh,map:qh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l={addresses:await Fh(e,n.addressFilter??(async()=>!0),o),protocols:[...s.values()].sort((f,d)=>f.localeCompare(d)),metadata:a,tags:c,publicKey:i?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:u};return e.type!=="RSA"&&delete l.publicKey,l}function Ho(e,t){let r=new Map;for(let[n,i]of e)i!=null&&t.validate(n,i);for(let[n,i]of e.sort(([o],[s])=>o.localeCompare(s)))i!=null&&r.set(n,t.map?.(n,i)??i);return r}function Kh(e,t){if(typeof e!="string")throw new A("Metadata key must be a string",Xt.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new A("Metadata value must be a Uint8Array",Xt.ERR_INVALID_PARAMETERS)}function Vh(e,t){if(typeof e!="string")throw new A("Tag name must be a string",Xt.ERR_INVALID_PARAMETERS);if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new A("Tag value must be an integer",Xt.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new A("Tag value must be between 0-100",Xt.ERR_INVALID_PARAMETERS)}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new A("Tag ttl must be an integer",Xt.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new A("Tag ttl must be between greater than 0",Xt.ERR_INVALID_PARAMETERS)}}function qh(e,t){let r;return t.expiry!=null&&(r=t.expiry),t.ttl!=null&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function Yo(e,t,r){let n=e.toString().split("/")[2],i=he.decode(n),o=kn(i),s=r.get(o);if(s!=null)return s;let a=$n(o,t);return r.set(o,a),a}function R2(e,t){return e==null?{}:{prefix:uu,filters:(e.filters??[]).map(r=>({key:n,value:i})=>r(Yo(n,i,t))),orders:(e.orders??[]).map(r=>(n,i)=>r(Yo(n.key,n.value,t),Yo(i.key,i.value,t)))}}var Wo=class{peerId;datastore;lock;addressFilter;constructor(t,r={}){this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=r.addressFilter,this.lock=cu({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(Hn(t))}async delete(t){if(this.peerId.equals(t))throw new A("Cannot delete self peer",Xt.ERR_INVALID_PARAMETERS);await this.datastore.delete(Hn(t))}async load(t){let r=await this.datastore.get(Hn(t));return $n(t,r)}async save(t,r){let{existingBuf:n,existingPeer:i}=await this.#t(t),o=await Go(t,r,"patch",{addressFilter:this.addressFilter});return this.#e(t,o,n,i)}async patch(t,r){let{existingBuf:n,existingPeer:i}=await this.#t(t),o=await Go(t,r,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#e(t,o,n,i)}async merge(t,r){let{existingBuf:n,existingPeer:i}=await this.#t(t),o=await Go(t,r,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#e(t,o,n,i)}async*all(t){let r=new le;for await(let{key:n,value:i}of this.datastore.query(R2(t??{},r))){let o=Yo(n,i,r);o.id.equals(this.peerId)||(yield o)}}async#t(t){try{let r=await this.datastore.get(Hn(t)),n=$n(t,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}}async#e(t,r,n,i){let o=zn.encode(r);return n!=null&&Et(o,n)?{peer:$n(t,o),previous:i,updated:!1}:(await this.datastore.put(Hn(t),o),{peer:$n(t,o),previous:i,updated:!0})}};var Qo=class{store;events;peerId;log;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Wo(t,r)}async forEach(t,r){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let i of this.store.all(r))t(i)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let r=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Ci(this.store.all(t))}finally{this.log.trace("all release read lock"),r()}}async delete(t){this.log.trace("delete await write lock");let r=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),r()}}async has(t){this.log.trace("has await read lock");let r=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),r()}}async get(t){this.log.trace("get await read lock");let r=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),r()}}async save(t,r){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let i=await this.store.save(t,r);return this.#t(t,i),i.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,r){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let i=await this.store.patch(t,r);return this.#t(t,i),i.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,r){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let i=await this.store.merge(t,r);return this.#t(t,i),i.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,r){let n=await Mn.openAndCertify(t,nn.DOMAIN);if(r?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;let i=nn.createFromProtobuf(n.payload),o;try{o=await this.get(n.peerId)}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(o?.peerRecordEnvelope!=null){let s=await Mn.createFromProtobuf(o.peerRecordEnvelope),a=nn.createFromProtobuf(s.payload);if(a.seqNumber>=i.seqNumber)return this.log("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:t,addresses:i.multiaddrs.map(s=>({isCertified:!0,multiaddr:s}))}),!0}#t(t,r){r.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))}};function T2(e){return e[Symbol.asyncIterator]!=null}function B2(e){if(T2(e))return(async()=>{for await(let t of e);})();for(let t of e);}var lu=B2;function L2(e){let[t,r]=e[Symbol.asyncIterator]!=null?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}var zh=L2;function D2(e){return e[Symbol.asyncIterator]!=null}function P2(e,t){if(D2(e))return async function*(){for await(let a of e)await t(a)&&(yield a)}();let r=zh(e),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of r)await t(a)&&(yield a)}();let s=t;return function*(){o===!0&&(yield n);for(let a of r)s(a)&&(yield a)}()}var an=P2;function N2(e){return e[Symbol.asyncIterator]!=null}function O2(e,t){return N2(e)?async function*(){yield*(await Ci(e)).sort(t)}():function*(){yield*Ci(e).sort(t)}()}var fu=O2;function k2(e){return e[Symbol.asyncIterator]!=null}function M2(e,t){return k2(e)?async function*(){let r=0;if(!(t<1)){for await(let n of e)if(yield n,r++,r===t)return}}():function*(){let r=0;if(!(t<1)){for(let n of e)if(yield n,r++,r===t)return}}()}var hu=M2;var Xo=class{put(t,r,n){return Promise.reject(new Error(".put is not implemented"))}get(t,r){return Promise.reject(new Error(".get is not implemented"))}has(t,r){return Promise.reject(new Error(".has is not implemented"))}delete(t,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,r={}){for await(let{key:n,value:i}of t)await this.put(n,i,r),yield n}async*getMany(t,r={}){for await(let n of t)yield{key:n,value:await this.get(n,r)}}async*deleteMany(t,r={}){for await(let n of t)await this.delete(n,r),yield n}batch(){let t=[],r=[];return{put(n,i){t.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await lu(this.putMany(t,n)),t=[],await lu(this.deleteMany(r,n)),r=[]}}}async*_all(t,r){throw new Error("._all is not implemented")}async*_allKeys(t,r){throw new Error("._allKeys is not implemented")}query(t,r){let n=this._all(t,r);if(t.prefix!=null){let i=t.prefix;n=an(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((i,o)=>an(i,o),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((i,o)=>fu(i,o),n)),t.offset!=null){let i=0,o=t.offset;n=an(n,()=>i++>=o)}return t.limit!=null&&(n=hu(n,t.limit)),n}queryKeys(t,r){let n=this._allKeys(t,r);if(t.prefix!=null){let i=t.prefix;n=an(n,o=>o.toString().startsWith(i))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((i,o)=>an(i,o),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((i,o)=>fu(i,o),n)),t.offset!=null){let i=t.offset,o=0;n=an(n,()=>o++>=i)}return t.limit!=null&&(n=hu(n,t.limit)),n}};var Gh=St(du(),1);function Yh(e){return e=e??new Error("Not Found"),(0,Gh.default)(e,"ERR_NOT_FOUND")}var Zo=class extends Xo{data;constructor(){super(),this.data=new Map}put(t,r){return this.data.set(t.toString(),r),t}get(t){let r=this.data.get(t.toString());if(r==null)throw Yh();return r}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,r]of this.data.entries())yield{key:new sn(t),value:r}}*_allKeys(){for(let t of this.data.keys())yield new sn(t)}};function Wh(e,t){let r;return function(){let n=function(){r=void 0,e()};clearTimeout(r),r=setTimeout(n,t)}}var K2=e=>e;function pu(e,t){let r=e.getPeerId();return r!=null&&Dt(r).equals(t)&&(e=e.decapsulate(_t(`/p2p/${t.toString()}`))),e}var Jo=class{log;components;listen;announce;observed;announceFilter;constructor(t,r={}){let{listen:n=[],announce:i=[]}=r;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(o=>o.toString()),this.announce=new Set(i.map(o=>o.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??K2,this._updatePeerStoreAddresses=Wh(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let t=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>_t(r))).map(r=>r.getPeerId()===this.components.peerId.toString()?r.decapsulate(`/p2p/${this.components.peerId.toString()}`):r);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(r=>{this.log.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(t=>_t(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>_t(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>_t(t))}addObservedAddr(t){t=pu(t,this.components.peerId);let r=t.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(t){t=pu(t,this.components.peerId);let r=t.toString(),i=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=pu(t,this.components.peerId);let r=t.toString();this.observed.delete(r)}getAddresses(){let t=this.getAnnounceAddrs().map(n=>n.toString());t.length===0&&(t=this.components.transportManager.getAddrs().map(n=>n.toString())),t=t.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let r=new Set(t);return this.announceFilter(Array.from(r).map(n=>_t(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var mu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[r,n]of Object.entries(t))this.components[r]=n;this.components.logger==null&&(this.components.logger=Do())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(r=>Sf(r)).map(async r=>{await r[t]?.()}))}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")}},V2=["metrics","connectionProtector"],q2=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Qh(e={}){let t=new mu(e);return new Proxy(t,{get(n,i,o){if(typeof i=="string"&&!q2.includes(i)){let s=t.components[i];if(s==null&&!V2.includes(i))throw new A(`${i} not set`,"ERR_SERVICE_MISSING");return s}return Reflect.get(n,i,o)},set(n,i,o){return typeof i=="string"?t.components[i]=o:Reflect.set(n,i,o),!0}})}var rd=St(Xh(),1);var Zh="[a-fA-F\\d:]",Br=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Zh})|(?<=${Zh})(?=\\s|$))`:"",Ne="(?: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}",Pt="[a-fA-F\\d]{1,4}",jo=`
|
|
8
16
|
(?:
|
|
9
|
-
(?:${
|
|
10
|
-
(?:${
|
|
11
|
-
(?:${
|
|
12
|
-
(?:${
|
|
13
|
-
(?:${
|
|
14
|
-
(?:${
|
|
15
|
-
(?:${
|
|
16
|
-
(?::(?:(?::${
|
|
17
|
+
(?:${Pt}:){7}(?:${Pt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
18
|
+
(?:${Pt}:){6}(?:${Ne}|:${Pt}|:)| // 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
|
|
19
|
+
(?:${Pt}:){5}(?::${Ne}|(?::${Pt}){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
|
|
20
|
+
(?:${Pt}:){4}(?:(?::${Pt}){0,1}:${Ne}|(?::${Pt}){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
|
|
21
|
+
(?:${Pt}:){3}(?:(?::${Pt}){0,2}:${Ne}|(?::${Pt}){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
|
|
22
|
+
(?:${Pt}:){2}(?:(?::${Pt}){0,3}:${Ne}|(?::${Pt}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
23
|
+
(?:${Pt}:){1}(?:(?::${Pt}){0,4}:${Ne}|(?::${Pt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
24
|
+
(?::(?:(?::${Pt}){0,5}:${Ne}|(?::${Pt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
17
25
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
18
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),ky=new RegExp(`(?:^${ht}$)|(?:^${ei}$)`),Ly=new RegExp(`^${ht}$`),Dy=new RegExp(`^${ei}$`),Jc=r=>r&&r.exact?ky:new RegExp(`(?:${ur(r)}${ht}${ur(r)})|(?:${ur(r)}${ei}${ur(r)})`,"g");Jc.v4=r=>r&&r.exact?Ly:new RegExp(`${ur(r)}${ht}${ur(r)}`,"g");Jc.v6=r=>r&&r.exact?Dy:new RegExp(`${ur(r)}${ei}${ur(r)}`,"g");var Yh=Jc;var Qh=dt(Xh(),1),{isValid:Py,parse:Oy}=Qh.default,My=["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"],Uy=My.map(r=>new Jh.Netmask(r));function Fy(r){for(let e of Uy)if(e.contains(r))return!0;return!1}function Zh(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 ed=r=>{if(Py(r)){let e=Oy(r);if(e.kind()==="ipv4")return Fy(e.toNormalizedString());if(e.kind()==="ipv6")return Zh(r)}else if(xn(r)&&Yh.v6().test(r))return Zh(r)};var ri=ed;function td(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ri(`${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}}var Vy=r=>r.toString().split("/").slice(1),fo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),ae=r=>({match:e=>fo(t=>t===r).match(e),pattern:r}),si=()=>({match:r=>fo(e=>typeof e=="string").match(r),pattern:"{string}"}),rd=()=>({match:r=>fo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),tt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ee.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ni=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ua.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),xt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),vt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),ce=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function we(...r){function e(o){let s=Vy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var el=ce(ae("dns4"),si()),tl=ce(ae("dns6"),si()),rl=ce(ae("dnsaddr"),si()),nd=ce(ae("dns"),si()),B_=we(el),C_=we(tl),T_=we(rl),N_=we(vt(nd,rl,el,tl)),od=ce(ae("ip4"),fo(Us)),sd=ce(ae("ip6"),fo(Fs)),id=vt(od,sd),ho=vt(id,nd,el,tl,rl),k_=we(ho),L_=we(od),D_=we(sd),P_=we(id),ii=ce(ho,ae("tcp"),rd()),po=ce(ho,ae("udp"),rd()),Ky=vt(ii,po),O_=we(ii),M_=we(po),nl=ce(po,ae("quic")),ai=ce(po,ae("quic-v1")),$y=vt(nl,ai),U_=we(nl),F_=we(ai),Qc=vt(ho,ii,po,nl,ai),ad=vt(ce(Qc,ae("ws"),xt(tt()))),V_=we(ad),cd=vt(ce(Qc,ae("wss"),xt(tt())),ce(Qc,ae("tls"),ae("ws"),xt(tt()))),K_=we(cd),ld=ce(Ky,ae("webrtc-direct"),ni(),xt(ni()),xt(tt())),$_=we(ld),ud=ce(ai,ae("webtransport"),ni(),ni(),xt(tt())),H_=we(ud),oi=vt(ad,cd,ce(ii,xt(tt())),ce($y,xt(tt())),ce(ho,xt(tt())),ld,ud,tt()),q_=we(oi),Hy=ce(oi,ae("p2p-circuit"),tt()),ol=we(Hy),qy=vt(ce(oi,ae("p2p-circuit"),ae("webrtc"),tt()),ce(oi,ae("webrtc"),xt(tt())),ae("webrtc")),z_=we(qy);function sl(r){try{let{address:e}=r.nodeAddress();return!!ri(e)}catch{return!0}}function zy(r,e){let t=sl(r.multiaddr),n=sl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Gy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function jy(r,e){let t=ol.exactMatch(r.multiaddr),n=ol.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Bn(r,e){let t=zy(r,e);if(t!==0)return t;let n=jy(r,e);return n!==0?n:Gy(r,e)}var al=dt(hc(),1),cl=dt(dd(),1);function ci(r,e,t){return`${r}?name=${e}&type=${t}`}async function pd(r,e){return await(await fetch(r,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function Or(r,e){return`${e}_${r}`}var il=Object.assign((0,al.default)("dns-over-http-resolver"),{error:(0,al.default)("dns-over-http-resolver:error")}),ll=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new cl.default({max:e?.maxCache??100}),this._TXTcache=new cl.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??pd,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),o=e[t];e[t]=e[n],e[n]=o}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(Or(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ci(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?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(Or(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ci(s,e,t),i.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?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(Or(e,t));if(n!=null)return n;let o=!1;for(let s of this._getShuffledServers()){let i=new AbortController;this._abortControllers.push(i);try{let a=await this._request(ci(s,e,t),i.signal),c=a.Answer.map(f=>[f.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(f=>f.TTL));return this._TXTcache.set(Or(e,t),c,{ttl:u}),c}catch{i.signal.aborted&&(o=!0),il.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==i)}}throw o?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},md=ll;var gd=md;var{code:Jy}=W("dnsaddr");async function Cn(r,e={}){let t=new gd;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,o]=r.stringTuples().find(([a])=>a===Jy)??[];if(o==null)throw new Error("No hostname found in multiaddr");let i=(await t.resolveTxt(`_dnsaddr.${o}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(i=i.filter(a=>a.includes(n))),i}var Id=dt(Rd(),1),fi=Id.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var C;(function(r){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_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_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"})(C||(C={}));var ow={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Cn},addressSorter:Bn},transportManager:{faultTolerance:Kt.FATAL_ALL}};function _d(r){let e=fi(ow,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,C.ERR_PROTECTOR_REQUIRED);return e}var Sd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},sw=new WeakMap;function iw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Sd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Sd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((p,h)=>{i=()=>{f(),p(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),sw.set(l,()=>{c(s),s=null,i()}),l}}var aw=iw(),Bd=aw;var hi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new fl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new E("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Bd(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&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)}},fl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function di(r){if(Eo(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:he(t),r.forEach(n=>{if(!ar(n))throw new E("Invalid Multiaddr",C.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",C.ERR_INVALID_PARAMETERS)}else{let s=he(o);if(e==null||!e.equals(s))throw new E("Multiaddrs must all have the same peer id or have no peer id",C.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var pi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return 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}},kn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pi(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 pi(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()}};var hl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mi(r={}){return cw(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 cw(r,e){e=e??{};let t=e.onEnd,n=new kn,o,s,i,a=pe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(b){y(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new kn,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},p=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),h=()=>(n=new kn,p(),{done:!0}),d=m=>(p(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:d,push:l,end:p,get readableLength(){return n.size},onEmpty:async m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,b;y!=null&&(w=new Promise((A,v)=>{b=()=>{v(new hl)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function gi(r,e,t,n){let o=new dl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{let a=u=>{n?.filter?.(u)!==!1&&(r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(u))},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var yi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ln(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new yi(t?.errorMessage,t?.errorCode));let n,o=new yi(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var wi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=pe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function lw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var bi=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=lw(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Xe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new $t)}async join(e={}){let t=new wi(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ln(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function uw(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Dn=class extends pr{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=uw(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new bi(e,t,t?.priority),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),s)).catch(s=>{throw this.safeDispatchEvent("error",{detail:s}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new $t)}),this.clear()}async onEmpty(e){this.size!==0&&await gi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await gi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gi(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=mi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new E("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ei=class extends Dn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var xi="last-dial-failure";var vi=5,Ai=100,Ri=50,Cd=1e3*60*7;var Mr={minConnections:vi,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Cd,autoDialDiscoveredPeersDebounce:10},Ii=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Mr.minConnections,this.autoDialPriority=t.autoDialPriority??Mr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Mr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Mr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Mr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Mr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ei({concurrency:t.autoDialConcurrency??Mr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new et(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new He;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,p=i.get(f.id)??0;return l>p?-1:l<p?1:0}).filter(u=>{let f=u.metadata.get(xi);if(f==null)return!0;let l=parseInt(V(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Td={maxConnections:Ai,allow:[]},_i=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Td.maxConnections,this.allow=t.allow??Td.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let o=new He;for(let a of e){let c=a.remotePeer;if(!o.has(c)){o.set(c,0);try{let u=await this.peerStore.get(c);o.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=o.get(a.remotePeer)??0,f=o.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let l=a.timeline.open,p=c.timeline.open;return l<p?1:l>p?-1:0}),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===n)break;await Promise.all(i.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:i})}};function Nd(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 o=e.signal;return o.clear=n,o}async function yl(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await dw(r,e),i=(await Promise.all(n.map(async a=>yl(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",r,i.map(a=>a.toString())),i}async function dw(r,e){try{return r=se(r.toString()),await r.resolve(e)}catch(t){return e.log.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}var Si={addressSorter:Bn,maxParallelDials:Ri,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:Cn}},Bi=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Si.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Si.maxPeerAddrsToDial,this.dialTimeout=t.dialTimeout??Si.dialTimeout,this.connections=t.connections??new He,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,Xe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Ks.set(n,o);this.queue=new Dn({concurrency:t.maxParallelDials??Si.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=di(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let p of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new E("Peer had more than maxPeerAddrsToDial",C.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(p.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",p.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",p.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[xi]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new E(h.message,vo);l.push(h)}}throw l.length===1?l[0]:new xo(l,"All multiaddr dials failed",C.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Nd([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return Xe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new E("Tried to dial self",C.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",C.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:p})=>p.toString()))}catch(l){if(l.code!==C.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:p})=>p.toString())),o.push(...l.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(l){l.code!==C.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let p=await yl(l.multiaddr,{...n,log:this.log});return p.length===1&&p[0].equals(l.multiaddr)?l:p.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(p=>p.multiaddr.protos().pop()?.path===!0?p:p.multiaddr.getPeerId()==null?{multiaddr:p.multiaddr.encapsulate(l),isCertified:p.isCertified}:p)}let i=s.filter(l=>{if(this.components.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let p=l.multiaddr.getPeerId();return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let l of i){let p=l.multiaddr.toString(),h=a.get(p);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(p,l)}let c=[...a.values()];if(c.length===0)throw new E("The dial request has no valid addresses",C.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new E("The connection gater denied all addresses in the dial request",C.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}};var gw=50,Ur={minConnections:vi,maxConnections:Ai,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ci=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ur.maxConnections;let n=t.minConnections??Ur.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",C.ERR_INVALID_PARAMETERS);this.connections=new He,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>se(o)),this.deny=(t.deny??[]).map(o=>se(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Ur.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new hi({points:t.inboundConnectionThreshold??Ur.inboundConnectionThreshold,duration:1}),this.autoDial=new Ii({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Ur.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Ur.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Ur.autoDialMaxQueueLength}),this.connectionPruner=new _i({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Bi(e,{addressSorter:t.addressSorter??Bn,maxParallelDials:t.maxParallelDials??Ri,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:Cn},connections:this.connections})}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.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 o of n.streams){let s=`${o.direction} ${o.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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Vl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.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(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.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,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=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 E("Not started",C.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=di(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??gw}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>se(n))}))}};function yw(r){return r[Symbol.asyncIterator]!=null}function ww(...r){let e=[];for(let t of r)yw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=mi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var mo=ww;var Ti=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 E("No content routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new et;for await(let s of mo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",C.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 E(Vt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Ni=globalThis.CustomEvent??Event;async function*El(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=pe(),a=pe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=pe(),await i.promise),f)break;let g={done:!1};s.push(g),d().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new Ni("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Ni("task-complete"))})}c=!0,o.dispatchEvent(new Ni("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ni("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*p(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*h(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let g=s[d];if(s.splice(d,1),d--,g.ok)yield g.value;else throw f=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(l()||(a=pe(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var ki=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",C.ERR_FIND_SELF);let n=this,o=mo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Vt.NOT_FOUND,C.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new et;for await(let s of El(async function*(){let i=mo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var xl=32,vl=64,Li=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new E(`No handler registered for protocol ${e}`,C.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 E(`Handler already registered for protocol ${e}`,C.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=fi.bind({ignoreUndefined:!0})({maxInboundStreams:xl,maxOutboundStreams:vl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new E("invalid topology",C.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),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).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.onDisconnect?.(t)}}).catch(n=>{n.code!==C.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.onDisconnect?.(t.id)}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(o,n)}}};var Al=class extends Map{metric;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 kd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Al({name:e,metrics:t}):n=new Map,n}var Di=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=kd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Kt.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new E("Transport must have a valid tag",C.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,C.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("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 E(`No transport available for address ${String(e)}`,C.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=C.ERR_TRANSPORT_DIAL_FAILED),o}}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(!this.isStarted())throw new E("Not started",C.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.filter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let p=l.findIndex(h=>h===f);l.splice(p,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Kt.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,C.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Kt.FATAL_ALL)throw new E(n,C.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),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 Ne="/multistream/1.0.0";var Rl=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=pe(),this.haveNext=pe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=pe(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pe(),await Ln(this.needNext.promise,t?.signal,t)}};function Ld(){return new Rl}var Pi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Il=class extends Pi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Dd(r,e){let t=Ld();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await 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 o=new xe;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Il("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:p}=await Promise.race([n.next(),u]);return l===!0?new xe:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Pi("unexpected end of input","ERR_UNEXPECTED_EOF");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}function Oi(r){return r[Symbol.asyncIterator]!=null}var Mi=r=>{let e=Me(r),t=Le(e);return qe(r,t),Mi.bytes=e,t};Mi.bytes=0;function Fr(r,e){e=e??{};let t=e.lengthEncoder??Mi;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Oi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Fr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mi;return new xe(t(r.byteLength),r)};var Pn=dt(Wc(),1);var bw=8,Ew=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Sl=r=>{let e=ft(r);return Sl.bytes=Me(e),e};Sl.bytes=0;function _l(r,e){let t=new xe,n=Vr.LENGTH,o=-1,s=e?.lengthDecoder??Sl,i=e?.maxLengthLength??bw,a=e?.maxDataLength??Ew;function*c(){for(;t.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(t),o<0)throw(0,Pn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Pn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Vr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw(0,Pn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Vr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Vr.LENGTH}}}return Oi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Pn.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,Pn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}_l.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return _l(n,{...e??{},onLength:s=>{t=s}})};var Ui=class extends Error{code;constructor(e,t){super(e),this.code=t}},Pd=r=>ft(r);Pd.bytes=0;function go(r,e={}){let t=Dd(r,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Me(e.maxDataLength)),{read:async o=>{let s=-1,i=new xe,a=e?.lengthDecoder??Pd;for(;;){i.append(await t.read(1,o));try{s=a(i)}catch(c){if(c instanceof RangeError)continue;throw c}if(e?.maxLengthLength!=null&&i.byteLength>e.maxLengthLength)throw new Ui("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new Ui("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(s,o)},write:async(o,s)=>{await t.write(Fr.single(o,e),s)},writeV:async(o,s)=>{let i=new xe(...o.map(a=>Fr.single(a,e)));await t.write(i,s)},unwrap:()=>t.unwrap()}}var vw=D(`
|
|
19
|
-
`);async function
|
|
20
|
-
`),
|
|
21
|
-
`);await
|
|
22
|
-
`),
|
|
23
|
-
`;yield new
|
|
24
|
-
`),
|
|
25
|
-
`),
|
|
26
|
-
`)]),
|
|
27
|
-
`),
|
|
28
|
-
`),
|
|
29
|
-
`))),
|
|
30
|
-
`));
|
|
31
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var _w=500,Bl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Fl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new E("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new E("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(_w);Xe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Ud(r){return new Bl(r)}var Bw=3e4;function Cw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return xl}function Tw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??vl}function Fd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Vi=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 o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new E(`The multiaddr connection is blocked by gater.${n}`,C.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",C.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",vo))};u.addEventListener("abort",f,{once:!0}),Xe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",C.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),l=await p.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let p={...l,...o};await this.shouldBlockConnection(s,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new E("inbound connection that skipped encryption must have a peer id",C.ERR_INVALID_MULTIADDR);let h=he(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let p=await this._multiplexInbound({...l,...o},this.muxers);a=p.muxerFactory,i=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=he(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new E("Encryption was skipped but no peer id was passed",C.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await wo(d,g,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let w=Cw(y,this.components.registrar);if(Fd(y,"inbound",l)===w){let A=new E(`Too many inbound protocol streams for protocol "${y}" - limit ${w}`,C.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=y,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:y})}).catch(async g=>{l.log.error("error handling incoming stream id %s",d.id,g.message,g.code,g.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,g={})=>{if(u==null)throw new E("Stream is not multiplexed",C.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(g.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(Bw);Xe(1/0,v),g={...g,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:y,protocol:w}=await yo(m,d,{...g,log:m.log,yieldBytes:!0});m.log("selected protocol %s",w);let b=Tw(w,this.components.registrar,g);if(Fd(w,"outbound",l)>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - limit ${b}`,C.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[w]}),m.source=y.source,m.sink=y.sink,m.protocol=w,y.closeWrite!=null&&(m.closeWrite=y.closeWrite),y.closeRead!=null&&(m.closeRead=y.closeRead),y.close!=null&&(m.close=y.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw l.log.error("could not create new stream for protocols %s",d,y),m.timeline.close==null&&m.abort(y),y.code!=null?y:new E(String(y),C.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let p=o.timeline;o.timeline=new Proxy(p,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&p.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(g){l.log.error("error closing connection after timeline close",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(g=>{l.log.error("error thrown while dispatching connection:close event",g)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",C.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Ud({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await wo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new E(n.message,C.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await yo(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %p",t),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new E(o.message,C.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await yo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new E(String(o),C.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await wo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),C.ERR_MUXER_UNAVAILABLE)}}};var Vd="1.1.1-856ccd708",Kd="libp2p";var Cl=class extends pr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new pr,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new ji(a.type,{detail:a.detail}));return c||u},Xe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ls(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=zh({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:Kd,version:Vd},logger:this.logger,events:t,datastore:e.datastore??new Js,connectionGater:td(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Xs(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Vi(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Di(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ci(this.components,e.connectionManager)),this.configureComponent("registrar",new Li(this.components)),this.configureComponent("addressManager",new Qs(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ki(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ti(this.components,{routers:i})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[$i]!=null&&(this.log("registering service %s for content routing",a),i.push(u[$i])),u[zi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[zi])),u[Hi]!=null&&(this.log("registering service %s for peer discovery",a),u[Hi].addEventListener?.("peer",f=>{this.#e(f)}))}}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new et;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,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new E("no protocols were provided to open a stream",C.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("no protocols were provided to open a stream",C.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,t={}){ar(e)&&(e=he(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==C.ERR_NOT_FOUND)throw s}let n=ge([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return to(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,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)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(C.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function $d(r={}){return r.peerId??=await sh(),new Cl(_d(r))}async function kw(r={}){let e=await $d(r);return r.start!==!1&&await e.start(),e}return rp(Lw);})();
|
|
26
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),z2=new RegExp(`(?:^${Ne}$)|(?:^${jo}$)`),$2=new RegExp(`^${Ne}$`),H2=new RegExp(`^${jo}$`),gu=e=>e&&e.exact?z2:new RegExp(`(?:${Br(e)}${Ne}${Br(e)})|(?:${Br(e)}${jo}${Br(e)})`,"g");gu.v4=e=>e&&e.exact?$2:new RegExp(`${Br(e)}${Ne}${Br(e)}`,"g");gu.v6=e=>e&&e.exact?H2:new RegExp(`${Br(e)}${jo}${Br(e)}`,"g");var Jh=gu;var nd=St(td(),1),{isValid:G2,parse:Y2}=nd.default,W2=["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"],Q2=W2.map(e=>new rd.Netmask(e));function X2(e){for(let t of Q2)if(t.contains(e))return!0;return!1}function ed(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}var id=e=>{if(G2(e)){let t=Y2(e);if(t.kind()==="ipv4")return X2(t.toNormalizedString());if(t.kind()==="ipv6")return ed(e)}else if(Fn(e)&&Jh.v6().test(e))return ed(e)};var es=id;function od(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{let r=t.stringTuples();return r[0][0]===4||r[0][0]===41?!!es(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}var Z2=e=>e.toString().split("/").slice(1),Pi=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),Rt=e=>({match:t=>Pi(r=>r===e).match(t),pattern:e}),is=()=>({match:e=>Pi(t=>typeof t=="string").match(e),pattern:"{string}"}),sd=()=>({match:e=>Pi(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),Se=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{vt.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),rs=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{_a.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),He=e=>({match:t=>{let r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),Ge=(...e)=>({match:t=>{let r;for(let n of e){let i=n.match(t);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${e.map(t=>t.pattern).join(", ")})`}),Tt=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function Mt(...e){function t(i){let o=Z2(i);for(let s of e){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return t(i)!==!1}function n(i){let o=t(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var xu=Tt(Rt("dns4"),is()),bu=Tt(Rt("dns6"),is()),vu=Tt(Rt("dnsaddr"),is()),ad=Tt(Rt("dns"),is()),lR=Mt(xu),fR=Mt(bu),hR=Mt(vu),dR=Mt(Ge(ad,vu,xu,bu)),cd=Tt(Rt("ip4"),Pi(Mo)),ud=Tt(Rt("ip6"),Pi(Uo)),ld=Ge(cd,ud),Ni=Ge(ld,ad,xu,bu,vu),pR=Mt(Ni),mR=Mt(cd),gR=Mt(ud),yR=Mt(ld),os=Tt(Ni,Rt("tcp"),sd()),Oi=Tt(Ni,Rt("udp"),sd()),J2=Ge(os,Oi),xR=Mt(os),bR=Mt(Oi),Eu=Tt(Oi,Rt("quic")),ss=Tt(Oi,Rt("quic-v1")),j2=Ge(Eu,ss),vR=Mt(Eu),ER=Mt(ss),yu=Ge(Ni,os,Oi,Eu,ss),fd=Ge(Tt(yu,Rt("ws"),He(Se()))),wR=Mt(fd),hd=Ge(Tt(yu,Rt("wss"),He(Se())),Tt(yu,Rt("tls"),Rt("ws"),He(Se()))),SR=Mt(hd),dd=Tt(J2,Rt("webrtc-direct"),rs(),He(rs()),He(Se())),AR=Mt(dd),pd=Tt(ss,Rt("webtransport"),rs(),rs(),He(Se())),IR=Mt(pd),ns=Ge(fd,hd,Tt(os,He(Se())),Tt(j2,He(Se())),Tt(Ni,He(Se())),dd,pd,Se()),_R=Mt(ns),tb=Tt(ns,Rt("p2p-circuit"),Se()),wu=Mt(tb),eb=Ge(Tt(ns,Rt("p2p-circuit"),Rt("webrtc"),Se()),Tt(ns,Rt("webrtc"),He(Se())),Rt("webrtc")),CR=Mt(eb);function Su(e){try{let{address:t}=e.nodeAddress();return!!es(t)}catch{return!0}}function rb(e,t){let r=Su(e.multiaddr),n=Su(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function nb(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function ib(e,t){let r=wu.exactMatch(e.multiaddr),n=wu.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Gn(e,t){let r=rb(e,t);if(r!==0)return r;let n=ib(e,t);return n!==0?n:nb(e,t)}var Iu=St(Bc(),1),_u=St(yd(),1);function as(e,t,r){return`${e}?name=${t}&type=${r}`}async function xd(e,t){return await(await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t})).json()}function cn(e,t){return`${t}_${e}`}var Au=Object.assign((0,Iu.default)("dns-over-http-resolver"),{error:(0,Iu.default)("dns-over-http-resolver:error")}),Cu=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(t={}){this._cache=new _u.default({max:t?.maxCache??100}),this._TXTcache=new _u.default({max:t?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=t.request??xd,this._abortControllers=[]}cancel(){this._abortControllers.forEach(t=>{t.abort()})}getServers(){return this._servers}_getShuffledServers(){let t=[...this._servers];for(let r=t.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=t[r];t[r]=t[n],t[n]=i}return t}setServers(t){this._servers=t}async resolve(t,r="A"){switch(r){case"A":return this.resolve4(t);case"AAAA":return this.resolve6(t);case"TXT":return this.resolveTxt(t);default:throw new Error(`${r} is not supported`)}}async resolve4(t){let r="A",n=this._cache.get(cn(t,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(as(o,t,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(cn(t,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Au.error(`${o} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolve6(t){let r="AAAA",n=this._cache.get(cn(t,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(as(o,t,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(cn(t,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Au.error(`${o} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolveTxt(t){let r="TXT",n=this._TXTcache.get(cn(t,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(as(o,t,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(cn(t,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Au.error(`${o} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},bd=Cu;var vd=bd;var{code:ub}=ut("dnsaddr");async function Yn(e,t={}){let r=new vd;t.signal!=null&&t.signal.addEventListener("abort",()=>{r.cancel()});let n=e.getPeerId(),[,i]=e.stringTuples().find(([a])=>a===ub)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var Td=St(Rd(),1),ls=Td.default;var cr;(function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"})(cr||(cr={}));var F;(function(e){e.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e.ERR_DIALED_SELF="ERR_DIALED_SELF",e.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e.ERR_INVALID_KEY="ERR_INVALID_KEY",e.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_PEER="ERR_INVALID_PEER",e.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e.ERR_NOT_FOUND="ERR_NOT_FOUND",e.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e.ERR_FIND_SELF="ERR_FIND_SELF",e.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e.ERR_INVALID_CMS="ERR_INVALID_CMS",e.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e.ERR_NO_KEY="ERR_NO_KEY",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var mb={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Yn},addressSorter:Gn},transportManager:{faultTolerance:dr.FATAL_ALL}};function Bd(e){let t=ls(mb,e);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new A(cr.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return t}var Ld=()=>{let e=new Error("Delay aborted");return e.name="AbortError",e},gb=new WeakMap;function yb({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(Ld());let o,s,a,c=e??clearTimeout,u=()=>{c(o),a(Ld())},l=()=>{i&&i.removeEventListener("abort",u)},f=new Promise((d,p)=>{s=()=>{l(),d(n)},a=p,o=(t??setTimeout)(s,r)});return i&&i.addEventListener("abort",u,{once:!0}),gb.set(f,()=>{c(o),o=null,s()}),f}}var xb=yb(),Dd=xb;var fs=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new Tu}async consume(t,r=1,n={}){let i=this.getKey(t),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,r,o);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+r&&(s=this.memoryStorage.set(i,s.consumedPoints,this.blockDuration)),new A("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let a=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=s.consumedPoints*this.execEvenlyMinDelayMs),await Dd(a)}return s}penalty(t,r=1,n={}){let i=this.getKey(t),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,r,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(t,r=1,n={}){let i=this.getKey(t),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,-r,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(t,r){let n=r*1e3,i=this.points+1;return this.memoryStorage.set(this.getKey(t),i,r),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:i,isFirstInDuration:!1}}set(t,r,n=0){let i=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),r,n),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:r,isFirstInDuration:!1}}get(t){let r=this.memoryStorage.get(this.getKey(t));return r!=null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),r}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},Tu=class{storage;constructor(){this.storage=new Map}incrby(t,r,n){let i=this.storage.get(t);if(i!=null){let o=i.expiresAt!=null?i.expiresAt.getTime()-new Date().getTime():-1;return i.expiresAt==null||o>0?(i.value+=r,{remainingPoints:0,msBeforeNext:o,consumedPoints:i.value,isFirstInDuration:!1}):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let i=n*1e3,o=this.storage.get(t);o!=null&&clearTimeout(o.timeoutId);let s={value:r,expiresAt:i>0?new Date(Date.now()+i):void 0};return this.storage.set(t,s),i>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(t)},i),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:s.value,isFirstInDuration:!0}}get(t){let r=this.storage.get(t);if(r!=null)return{remainingPoints:0,msBeforeNext:r.expiresAt!=null?r.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:r.value,isFirstInDuration:!1}}delete(t){let r=this.storage.get(t);return r!=null?(r.timeoutId!=null&&clearTimeout(r.timeoutId),this.storage.delete(t),!0):!1}};function hs(e){if(oo(e))return{peerId:e,multiaddrs:[]};Array.isArray(e)||(e=[e]);let t;if(e.length>0){let r=e[0].getPeerId();t=r==null?void 0:Dt(r),e.forEach(n=>{if(!Cr(n))throw new A("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(t!=null)throw new A("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let o=Dt(i);if(t==null||!t.equals(o))throw new A("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}function Nt(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var ds=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Xn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ds(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new ds(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Bu=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function ps(e={}){return bb(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function bb(e,t){t=t??{};let r=t.onEnd,n=new Xn,i,o,s,a=Nt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((g,y)=>{o=x=>{o=null,n.push(x);try{g(e(n))}catch(b){y(b)}return i}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Nt()})}},u=g=>o!=null?o(g):(n.push(g),i),l=g=>(n=new Xn,o!=null?o({error:g}):(n.push({error:g}),i)),f=g=>{if(s)return i;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>s?i:(s=!0,g!=null?l(g):u({done:!0})),p=()=>(n=new Xn,d(),{done:!0}),h=g=>(d(g),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let x,b;y!=null&&(x=new Promise((_,w)=>{b=()=>{w(new Bu)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),r!=null&&(r(g),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(g){return m.end(g),r!=null&&(r(g),r=void 0),i},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},i}var Lu=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function ms(e,t,r,n){let i=new Lu(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(i):new Promise((o,s)=>{let a=u=>{n?.filter?.(u)!==!1&&(e.removeEventListener(t,a),r?.removeEventListener("abort",c),o(u))},c=()=>{e.removeEventListener(t,a),r?.removeEventListener("abort",c),s(i)};e.addEventListener(t,a),r?.addEventListener("abort",c)})}var gs=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function Zn(e,t,r){if(t==null)return e;if(t.aborted)return Promise.reject(new gs(r?.errorMessage,r?.errorCode));let n,i=new gs(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((o,s)=>{n=()=>{s(i)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ys=class{deferred;signal;where;constructor(t,r){this.signal=r,this.deferred=Nt(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new pr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xs=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,r,n=0){this.id=vb(),this.status="queued",this.fn=t,this.priority=n,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,be(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((r,n)=>r&&n.signal?.aborted===!0,!0)&&this.controller.abort(new pr)}async join(t={}){let r=new ys(new Error("where").stack,t.signal);return this.recipients.push(r),t.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Zn(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(r=>{r.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.signal?.removeEventListener("abort",this.onAbort)})}};function Eb(e,t,r){let n=0,i=e.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(e[s],t)<=0?(n=++s,i-=o+1):i=o}return n}var Jn=class extends Fr{concurrency;queue;pending;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let r of this.queue)if(r.status==="queued"){t=r;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===t){this.queue.splice(r,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let r=Eb(this.queue,t,(n,i)=>i.priority-n.priority);this.queue.splice(r,0,t)}async add(t,r){r?.signal?.throwIfAborted();let n=new xs(t,r,r?.priority),i=n.join(r).then(o=>(this.safeDispatchEvent("completed",{detail:o}),o)).catch(o=>{throw this.safeDispatchEvent("error",{detail:o}),o});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new pr)}),this.clear()}async onEmpty(t){this.size!==0&&await ms(this,"empty",t?.signal)}async onSizeLessThan(t,r){this.size<t||await ms(this,"next",r?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ms(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let r=ps({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},i=c=>{c.detail!=null&&r.push(c.detail)},o=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new A("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",i),this.addEventListener("error",o),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",i),this.removeEventListener("error",o),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var bs=class extends Jn{has(t){return this.find(t)!=null}find(t){return this.queue.find(r=>t.equals(r.options.peerId))}};var vs="last-dial-failure";var Es=5,ws=100,Ss=50,Pd=1e3*60*7;var un={minConnections:Es,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Pd,autoDialDiscoveredPeersDebounce:10},As=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(t,r){this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.minConnections=r.minConnections??un.minConnections,this.autoDialPriority=r.autoDialPriority??un.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??un.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??un.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??un.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??un.autoDialDiscoveredPeersDebounce,this.log=t.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new bs({concurrency:r.autoDialConcurrency??un.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:t.metrics}),this.queue.addEventListener("error",i=>{this.log.error("error during auto-dial",i.detail)}),t.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{this.log.error(i)})});let n;t.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{this.log.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(t=>{this.log.error("error while autodialing",t)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let t=this.connectionManager.getConnectionsMap(),r=t.size;if(r>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",r,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new we(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):t.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new le;for(let u of o)s.has(u.id)||s.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=o.sort((u,l)=>{let f=s.get(u.id)??0,d=s.get(l.id)??0;return f>d?-1:f<d?1:0}).filter(u=>{let l=u.metadata.get(vs);if(l==null)return!0;let f=parseInt(it(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});this.log("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){this.log("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{this.log.error("could not connect to peerStore stored peer",l)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(t=>{this.log.error("error while autodialing",t)})},this.autoDialIntervalMs))}};var Nd={maxConnections:ws,allow:[]},Is=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,r={}){this.maxConnections=r.maxConnections??Nd.maxConnections,this.allow=r.allow??Nd.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),t.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let t=this.connectionManager.getConnections(),r=t.length,n=Math.max(r-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new le;for(let a of t){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,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=t.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 f=a.timeline.open,d=c.timeline.open;return f<d?1:f>d?-1:0}),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};function Od(e){let t=new globalThis.AbortController;function r(){t.abort();for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of e){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=t.signal;return i.clear=n,i}async function Ou(e,t){if(!e.protoNames().includes("dnsaddr"))return[e];let n=await Ab(e,t),s=(await Promise.all(n.map(async a=>Ou(a,t)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return t.log("resolved %s to",e,s.map(a=>a.toString())),s}async function Ab(e,t){try{return e=_t(e.toString()),await e.resolve(t)}catch(r){return t.log.error(`multiaddr ${e.toString()} could not be resolved`,r),[]}}var _s={addressSorter:Gn,maxParallelDials:Ss,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:Yn}},Cs=class{queue;components;addressSorter;maxPeerAddrsToDial;dialTimeout;shutDownController;connections;log;constructor(t,r={}){this.addressSorter=r.addressSorter??_s.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??_s.maxPeerAddrsToDial,this.dialTimeout=r.dialTimeout??_s.dialTimeout,this.connections=r.connections??new le,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,be(1/0,this.shutDownController.signal);for(let[n,i]of Object.entries(r.resolvers??{}))Ko.set(n,i);this.queue=new Jn({concurrency:r.maxParallelDials??_s.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,r={}){let{peerId:n,multiaddrs:i}=hs(t),o=Array.from(this.connections.values()).flat().find(a=>r.force===!0?!1:a.remotePeer.equals(n)?!0:i.find(c=>c.equals(a.remoteAddr)));if(o!=null)return this.log("already connected to %a",o.remoteAddr),o;let s=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of i)if(c.has(u.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let a of i)s.options.multiaddrs.add(a.toString());return s.join(r)}return this.log("creating dial target for %p",n,i.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:l})=>l.toString()).forEach(l=>{a?.multiaddrs.add(l)})}catch(l){throw c.clear(),l}try{let l=0,f=[];for(let d of u){if(l===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",l,n),new A("Peer had more than maxPeerAddrsToDial",F.ERR_TOO_MANY_ADDRESSES);l++;try{let p=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",d.multiaddr),p}catch(p){if(this.log.error("dial failed to %a",d.multiaddr,p),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[vs]:Y(Date.now().toString())}})}catch(h){this.log.error("could not update last dial failure key for %p",n,h)}if(c.aborted)throw new A(p.message,ao);f.push(p)}}throw f.length===1?f[0]:new so(f,"All multiaddr dials failed",F.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:r.priority,multiaddrs:new Set(i.map(a=>a.toString())),signal:r.signal})}createDialAbortController(t){let r=Od([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,t]);return be(1/0,r),r}async calculateMultiaddrs(t,r=new Set,n={}){let i=[...r].map(f=>({multiaddr:_t(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new A("Tried to dial self",F.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new A("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(i.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);i.push(...f.addresses),this.log("loaded multiaddrs for %p",t,i.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.code!==F.ERR_NOT_FOUND)throw f}}if(i.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let f=await this.components.peerRouting.findPeer(t);this.log("found multiaddrs for %p in the peer routing",t,i.map(({multiaddr:d})=>d.toString())),i.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.code!==F.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",t,f)}}}let o=(await Promise.all(i.map(async f=>{let d=await Ou(f.multiaddr,{...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(p=>({multiaddr:p,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;o=o.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let s=o.filter(f=>{if(this.components.transportManager.transportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of s){let d=f.multiaddr.toString(),p=a.get(d);if(p!=null){p.isCertified=p.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new A("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=u.sort(this.addressSorter);if(l.length===0)throw new A("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",t??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}};var Cb=50,ln={minConnections:Es,maxConnections:ws,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Rs=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(t,r={}){this.maxConnections=r.maxConnections??ln.maxConnections;let n=r.minConnections??ln.minConnections;if(this.maxConnections<n)throw new A("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new le,this.started=!1,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>_t(i)),this.deny=(r.deny??[]).map(i=>_t(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??ln.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new fs({points:r.inboundConnectionThreshold??ln.inboundConnectionThreshold,duration:1}),this.autoDial=new As({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??ln.autoDialConcurrency,autoDialPriority:r.autoDialPriority??ln.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??ln.autoDialMaxQueueLength}),this.connectionPruner=new Is({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Cs(t,{addressSorter:r.addressSorter??Gn,maxParallelDials:r.maxParallelDials??Ss,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Yn},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?t.inbound++:t.outbound++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;t[o]=(t[o]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))t[s]=t[s]??[],t[s].push(a)}let r={};for(let[n,i]of Object.entries(t)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[r=>r.tags.has(Ef)]});await Promise.all(t.map(async r=>{await this.openConnection(r.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let t=[];for(let r of this.connections.values())for(let n of r)t.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}onConnect(t){this._onConnect(t).catch(r=>{this.log.error(r)})}async _onConnect(t){let{detail:r}=t;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(t){let{detail:r}=t;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(t,r={}){if(!this.isStarted())throw new A("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=hs(t);if(n!=null&&r.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let i=await this.dialQueue.dial(t,{...r,priority:r.priority??Cb}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(t,r={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(t){if(this.deny.some(i=>t.remoteAddr.toString().startsWith(i.toString())))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(i=>t.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let i=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(r=>({id:r.id,status:t[r.status],peerId:r.options.peerId,multiaddrs:[...r.options.multiaddrs].map(n=>_t(n))}))}};function Rb(e){return e[Symbol.asyncIterator]!=null}function Tb(...e){let t=[];for(let r of e)Rb(r)||t.push(r);return t.length===e.length?function*(){for(let r of t)yield*r}():async function*(){let r=ps({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var ki=Tb;var Ts=class{routers;started;components;constructor(t,r){this.routers=r.routers??[],this.started=!1,this.components=t}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,r={}){if(this.routers.length===0)throw new A("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);let n=this,i=new we;for await(let o of ki(...n.routers.map(s=>s.findProviders(t,r))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!i.has(o.id)&&(i.add(o.id),yield o))}async provide(t,r={}){if(this.routers.length===0)throw new A("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(t,r)}))}async put(t,r,n){if(!this.isStarted())throw new A(cr.NOT_STARTED_YET,F.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(t,r,n)}))}async get(t,r){if(!this.isStarted())throw new A(cr.NOT_STARTED_YET,F.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(t,r)))}};var Bs=globalThis.CustomEvent??Event;async function*Uu(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);let n=t.ordered==null?!1:t.ordered,i=new EventTarget,o=[],s=Nt(),a=Nt(),c=!1,u,l=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of e){if(o.length===r&&(s=Nt(),await s.promise),l)break;let m={done:!1};o.push(m),h().then(g=>{m.done=!0,m.ok=!0,m.value=g,i.dispatchEvent(new Bs("task-complete"))},g=>{m.done=!0,m.err=g,i.dispatchEvent(new Bs("task-complete"))})}c=!0,i.dispatchEvent(new Bs("task-complete"))}catch(h){u=h,i.dispatchEvent(new Bs("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(h=>h.done)}function*d(){for(;o.length>0&&o[0].done;){let h=o[0];if(o.shift(),h.ok)yield h.value;else throw l=!0,s.resolve(),h.err;s.resolve()}}function*p(){for(;f();)for(let h=0;h<o.length;h++)if(o[h].done){let m=o[h];if(o.splice(h,1),h--,m.ok)yield m.value;else throw l=!0,s.resolve(),m.err;s.resolve()}}for(;;){if(f()||(a=Nt(),await a.promise),u!=null)throw u;if(n?yield*d():yield*p(),c&&o.length===0)break}}var Ls=class{log;peerId;peerStore;routers;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=r.routers??[]}async findPeer(t,r){if(this.routers.length===0)throw new A("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(t.toString()===this.peerId.toString())throw new A("Should not try to find self",F.ERR_FIND_SELF);let n=this,i=ki(...this.routers.map(o=>async function*(){try{yield await o.findPeer(t,r)}catch(s){n.log.error(s)}}()));for await(let o of i)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new A(cr.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(t,r={}){if(this.routers.length===0)throw new A("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);let n=this,i=new we;for await(let o of Uu(async function*(){let s=ki(...n.routers.map(a=>a.getClosestPeers(t,r)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...r,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!i.has(o.id)&&(i.add(o.id),yield o))}};var Fu=32,Ku=64,Ds=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let r=this.handlers.get(t);if(r==null)throw new A(`No handler registered for protocol ${t}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(t){let r=this.topologies.get(t);return r==null?[]:[...r.values()]}async handle(t,r,n){if(this.handlers.has(t))throw new A(`Handler already registered for protocol ${t}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=ls.bind({ignoreUndefined:!0})({maxInboundStreams:Fu,maxOutboundStreams:Ku},n);this.handlers.set(t,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,r){if(r==null)throw new A("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(t);return i==null&&(i=new Map,this.topologies.set(t,i)),i.set(n,r),n}unregister(t){for(let[r,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(r))}_onDisconnect(t){let r=t.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",r,n)})}_onPeerUpdate(t){let{peer:r,previous:n}=t.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o));for(let o of i){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onDisconnect?.(r.id)}}_onPeerIdentify(t){let r=t.detail.protocols,n=t.detail.connection,i=t.detail.peerId;for(let o of r){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(i,n)}}};var Vu=class extends Map{metric;constructor(t){super();let{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(t,r){return super.set(t,r),this.updateComponentMetric(),this}delete(t){let r=super.delete(t);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function kd(e){let{name:t,metrics:r}=e,n;return r!=null?n=new Vu({name:t,metrics:r}):n=new Map,n}var Ps=class{log;components;transports;listeners;faultTolerance;started;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=kd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??dr.FATAL_ALL}add(t){let r=t[Symbol.toStringTag];if(r==null)throw new A("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new A(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",r),this.transports.set(r,t),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[r,n]of this.listeners)for(this.log("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&t.push(i.close())}await Promise.all(t),this.log("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(t,r){let n=this.transportForMultiaddr(t);if(n==null)throw new A(`No transport available for address ${String(t)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(t,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let t=[];for(let r of this.listeners.values())for(let n of r)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(t){for(let r of this.transports.values())if(r.filter([t]).length>0)return r}async listen(t){if(!this.isStarted())throw new A("Not started",F.ERR_NODE_NOT_STARTED);if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(t),s=[];for(let u of o){this.log("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=f.findIndex(p=>p===l);f.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==dr.NO_FATAL)throw new A(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===dr.FATAL_ALL)throw new A(n,F.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(t){let r=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let r of this.transports.keys())t.push(this.remove(r));await Promise.all(t)}};var Zt="/multistream/1.0.0";var qu=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=Nt(),this.haveNext=Nt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let t=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=Nt(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,r){await this._push(t,r)}async end(t,r){t!=null?await this.throw(t):await this._push(void 0,r)}async _push(t,r){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Nt(),await Zn(this.needNext.promise,r?.signal,r)}};function Md(){return new qu}var Ns=class extends Error{code;constructor(t,r){super(t),this.code=r}},zu=class extends Ns{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Ud(e,t){let r=Md();e.sink(r).catch(async s=>{await r.end(s)}),e.sink=async s=>{for await(let a of s)await r.push(a);await r.end()};let n=e.source;e.source[Symbol.iterator]!=null?n=e.source[Symbol.iterator]():e.source[Symbol.asyncIterator]!=null&&(n=e.source[Symbol.asyncIterator]());let i=new qt;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((l,f)=>{c=()=>{f(new zu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:f,value:d}=await Promise.race([n.next(),u]);return f===!0?new qt:d}for(;i.byteLength<s;){let{value:f,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new Ns("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(f)}let l=i.sublist(0,s);return i.consume(s),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await r.push(s,a):await r.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=e.source;e.source=async function*(){t?.yieldBytes===!1?yield i:yield*i,yield*s}()}return e}}}function Os(e){return e[Symbol.asyncIterator]!=null}var ks=e=>{let t=re(e),r=jt(t);return fe(e,r),ks.bytes=t,r};ks.bytes=0;function fn(e,t){t=t??{};let r=t.lengthEncoder??ks;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Os(e)?async function*(){for await(let i of e)yield*n(i)}():function*(){for(let i of e)yield*n(i)}()}fn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??ks;return new qt(r(e.byteLength),e)};var jn=St(du(),1);var Bb=8,Lb=1024*1024*4,hn;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(hn||(hn={}));var Hu=e=>{let t=Pe(e);return Hu.bytes=re(t),t};Hu.bytes=0;function $u(e,t){let r=new qt,n=hn.LENGTH,i=-1,o=t?.lengthDecoder??Hu,s=t?.maxLengthLength??Bb,a=t?.maxDataLength??Lb;function*c(){for(;r.byteLength>0;){if(n===hn.LENGTH)try{if(i=o(r),i<0)throw(0,jn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,jn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),t?.onLength!=null&&t.onLength(i),n=hn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,jn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===hn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),t?.onData!=null&&t.onData(u),yield u,n=hn.LENGTH}}}return Os(e)?async function*(){for await(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,jn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,jn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}$u.fromReader=(e,t)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await e.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return $u(n,{...t??{},onLength:o=>{r=o}})};var Ms=class extends Error{code;constructor(t,r){super(t),this.code=r}},Fd=e=>Pe(e);Fd.bytes=0;function Mi(e,t={}){let r=Ud(e,t);return t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=re(t.maxDataLength)),{read:async i=>{let o=-1,s=new qt,a=t?.lengthDecoder??Fd;for(;;){s.append(await r.read(1,i));try{o=a(s)}catch(c){if(c instanceof RangeError)continue;throw c}if(t?.maxLengthLength!=null&&s.byteLength>t.maxLengthLength)throw new Ms("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(o>-1)break}if(t?.maxDataLength!=null&&o>t.maxDataLength)throw new Ms("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(o,i)},write:async(i,o)=>{await r.write(fn.single(i,t),o)},writeV:async(i,o)=>{let s=new qt(...i.map(a=>fn.single(a,t)));await r.write(s,o)},unwrap:()=>r.unwrap()}}var Pb=Y(`
|
|
27
|
+
`);async function dn(e,t,r){await e.write(t,r)}async function Kd(e,t,r){await e.writeV(t,r)}async function Nb(e,t){let r=await e.read(t);if(r.byteLength===0||r.get(r.byteLength-1)!==Pb[0])throw t.log.error("Invalid mss message - missing newline",r),new A("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function Dr(e,t){let r=await Nb(e,t);return it(r.subarray())}async function Ui(e,t,r){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&r.negotiateFully===!1)return Ob(e,t[0],r);let n=Mi(e,{...r,maxDataLength:1024}),i=t.shift();if(i==null)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Zt,i);let o=Y(`${Zt}
|
|
28
|
+
`),s=Y(`${i}
|
|
29
|
+
`);await Kd(n,[o,s],r),r.log.trace("select: reading multistream-select header");let a=await Dr(n,r);if(r.log.trace('select: read "%s"',a),a===Zt&&(r.log.trace("select: reading protocol response"),a=await Dr(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let c of t){r.log.trace('select: write "%s"',c),await dn(n,Y(`${c}
|
|
30
|
+
`),r),r.log.trace("select: reading protocol response");let u=await Dr(n,r);if(r.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new A("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Ob(e,t,r){let n=e.sink.bind(e),i=e.source,o=!1,s=!1,a=Nt(),c=!1,u=!1,l=Nt(),f=!1,d=!1,p=Nt(),h=Mi({sink:n,source:i},{...r,maxDataLength:1024});e.sink=async x=>{let{sink:b}=h.unwrap();await b(async function*(){let _=!1;for await(let w of x){if(u&&await l.promise,c)yield w;else{u=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Zt,t,w.byteLength);let S=`${t}
|
|
31
|
+
`;yield new qt(Uint8Array.from([19]),Y(`${Zt}
|
|
32
|
+
`),fe(S.length),Y(S),w).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Zt,t,w.byteLength),c=!0,u=!1,l.resolve(),m().catch(D=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,D)})}_=!0}_||await m()}())};async function m(){if(s){r.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}s=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await g()),f||(r.log.trace("optimistic: doing read protocol for %s stream",t),await y())}finally{s=!1,o=!0,a.resolve()}}async function g(){if(u){await l.promise;return}u=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Zt,t),await h.writeV([Y(`${Zt}
|
|
33
|
+
`),Y(`${t}
|
|
34
|
+
`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Zt,t)}finally{c=!0,u=!1,l.resolve()}}async function y(){if(d){await p.promise;return}d=!0;try{r.log.trace("optimistic: reading multistream select header");let x=await Dr(h,r);if(r.log.trace('optimistic: read multistream select header "%s"',x),x===Zt&&(x=await Dr(h,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',x,t),x!==t)throw new A("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{f=!0,d=!1,p.resolve()}}if(e.source=async function*(){await m(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*h.unwrap().source}(),e.closeRead!=null){let x=e.closeRead.bind(e);e.closeRead=async b=>{o||await m().catch(_=>{r.log.error("could not negotiate protocol before close read",_)}),await x(b)}}if(e.closeWrite!=null){let x=e.closeWrite.bind(e);e.closeWrite=async b=>{o||await m().catch(_=>{r.log.error("could not negotiate protocol before close write",_)}),await x(b)}}if(e.close!=null){let x=e.close.bind(e);e.close=async b=>{let _=[];u&&_.push(l.promise),d&&_.push(p.promise),_.length>0?await Zn(Promise.all(_),b?.signal):(o=!0,s=!1,a.resolve()),await x(b)}}return{stream:e,protocol:t}}async function Fi(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);let n=Mi(e,{...r,maxDataLength:1024,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");let i=await Dr(n,r);if(r.log.trace('handle: read "%s"',i),i===Zt){r.log.trace('handle: respond with "%s" for "%s"',Zt,i),await dn(n,Y(`${Zt}
|
|
35
|
+
`),r),r.log.trace('handle: responded with "%s" for "%s"',Zt,i);continue}if(t.includes(i))return r.log.trace('handle: respond with "%s" for "%s"',i,i),await dn(n,Y(`${i}
|
|
36
|
+
`),r),r.log.trace('handle: responded with "%s" for "%s"',i,i),{stream:n.unwrap(),protocol:i};if(i==="ls"){let o=new qt(...t.map(s=>fn.single(Y(`${s}
|
|
37
|
+
`))),Y(`
|
|
38
|
+
`));r.log.trace('handle: respond with "%s" for %s',t,i),await dn(n,o,r),r.log.trace('handle: responded with "%s" for %s',t,i);continue}r.log('handle: respond with "na" for "%s"',i),await dn(n,Y(`na
|
|
39
|
+
`),r),r.log('handle: responded with "na" for "%s"',i)}}var Mb=500,Gu=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:s,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.transient=t.transient??!1,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=i,this._close=o,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[vf]=!0;get streams(){return this._getStreams()}async newStream(t,r){if(this.status==="closing")throw new A("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new A("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(t)||(t=[t]),this.transient&&r?.runOnTransientConnection!==!0)throw new A("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(t,r);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let r=AbortSignal.timeout(Mb);be(1/0,r),t={...t,signal:r}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(t))),this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(r){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(t){this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(r=>{r.abort(t)}),this.log.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}};function qd(e){return new Gu(e)}var Fb=3e4;function Kb(e,t){try{let{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(r){if(r.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Fu}function Vb(e,t,r={}){try{let{options:n}=t.getHandler(e);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??Ku}function zd(e,t,r){let n=0;return r.streams.forEach(i=>{i.direction===t&&i.protocol===e&&n++}),n}var Fs=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(t,r){this.components=t,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=t.events}async shouldBlockConnection(t,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(t,r))throw new A(`The multiaddr connection is blocked by gater.${n}`,F.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(t,r){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new A("connection denied",F.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{t.abort(new A("inbound upgrade timeout",ao))};u.addEventListener("abort",l,{once:!0}),be(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new A("The multiaddr connection is blocked by gater.acceptConnection",F.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the inbound connection upgrade");let f=t;if(r?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the inbound connection"),f=await d.protect(t))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(f));let d={...f,...i};await this.shouldBlockConnection(o,d,"denyInboundEncryptedConnection")}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new A("inbound connection that skipped encryption must have a peer id",F.ERR_INVALID_MULTIADDR);let p=Dt(d);c="native",o=p}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let d=await this._multiplexInbound({...f,...i},this.muxers);a=d.muxerFactory,s=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(o,t,"denyInboundUpgradedConnection"),t.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:t,upgradedConn:s,muxerFactory:a,remotePeer:o,transient:r?.transient})}finally{u.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,r){let n=t.remoteAddr.getPeerId(),i;n!=null&&(i=Dt(n),await this.shouldBlockConnection(i,t,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the outbound connection upgrade");let l=t;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(t))}try{if(o=l,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...o};await this.shouldBlockConnection(s,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new A("Encryption was skipped but no peer id was passed",F.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...o},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw t.log.error("failed to upgrade outbound connection",f),await t.close(f),f}return await this.shouldBlockConnection(s,t,"denyOutboundUpgradedConnection"),t.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:t,upgradedConn:a,muxerFactory:u,remotePeer:s,transient:r?.transient})}_createConnection(t){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a,transient:c}=t,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:h=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await Fi(h,m,{log:h.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",y);let x=Kb(y,this.components.registrar);if(zd(y,"inbound",f)===x){let _=new A(`Too many inbound protocol streams for protocol "${y}" - limit ${x}`,F.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw h.abort(_),_}h.source=g.source,h.sink=g.sink,h.protocol=y,g.closeWrite!=null&&(h.closeWrite=g.closeWrite),g.closeRead!=null&&(h.closeRead=g.closeRead),g.close!=null&&(h.close=g.close),await this.components.peerStore.merge(s,{protocols:[y]}),this.components.metrics?.trackProtocolStream(h,f),this._onStream({connection:f,stream:h,protocol:y})}).catch(async m=>{f.log.error("error handling incoming stream id %s",h.id,m.message,m.code,m.stack),h.timeline.close==null&&await h.close()})}}),l=async(h,m={})=>{if(u==null)throw new A("Stream is not multiplexed",F.ERR_MUXER_UNAVAILABLE);f.log("starting new stream for protocols %s",h);let g=await u.newStream();f.log.trace("started new stream %s for protocols %s",g.id,h);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",h);let w=AbortSignal.timeout(Fb);be(1/0,w),m={...m,signal:w}}g.log.trace("selecting protocol from protocols %s",h);let{stream:y,protocol:x}=await Ui(g,h,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",x);let b=Vb(x,this.components.registrar,m);if(zd(x,"outbound",f)>=b){let w=new A(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,F.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(w),w}return await this.components.peerStore.merge(s,{protocols:[x]}),g.source=y.source,g.sink=y.sink,g.protocol=x,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,f),g}catch(y){throw f.log.error("could not create new stream for protocols %s",h,y),g.timeline.close==null&&g.abort(y),y.code!=null?y:new A(String(y),F.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(h=>{f.log.error("error piping data through muxer",h)}));let d=i.timeline;i.timeline=new Proxy(d,{set:(...h)=>(f!=null&&h[1]==="close"&&h[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){f.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{f.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...h))}),i.timeline.upgraded=Date.now();let p=()=>{throw new A("connection is not multiplexed",F.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=qd({remoteAddr:i.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,logger:this.components.logger,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async h=>{u!=null&&(f.log.trace("close muxer"),await u.close(h)),f.log.trace("close maconn"),await i.close(h),f.log.trace("closed maconn")},abort:h=>{i.abort(h),u?.abort(h)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(t){let{connection:r,stream:n,protocol:i}=t,{handler:o,options:s}=this.components.registrar.getHandler(i);if(r.transient&&s.runOnTransientConnection!==!0)throw new A("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");o({connection:r,stream:n})}async _encryptInbound(t){let r=Array.from(this.connectionEncryption.keys());t.log("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await Fi(t,r,{log:t.log}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return t.log("encrypting inbound connection using",i),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw t.log.error("encrypting inbound connection to %p failed",n),new A(n.message,F.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(t,r){let n=Array.from(this.connectionEncryption.keys());t.log("selecting outbound crypto protocol",n);try{t.log.trace("selecting encrypter from %s",n);let{stream:i,protocol:o}=await Ui(t,n,{log:t.log,yieldBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return t.log("encrypting outbound connection to %p using %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw t.log.error("encrypting outbound connection to %p failed",i),new A(i.message,F.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(t,r){let n=Array.from(r.keys());t.log("outbound selecting muxer %s",n);try{t.log.trace("selecting stream muxer from %s",n);let{stream:i,protocol:o}=await Ui(t,n,{log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw t.log.error("error multiplexing outbound connection",i),new A(String(i),F.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(t,r){let n=Array.from(r.keys());t.log("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await Fi(t,n,{log:t.log}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw t.log.error("error multiplexing inbound connection",i),new A(String(i),F.ERR_MUXER_UNAVAILABLE)}}};var $d="1.1.1-ddaa59a60",Hd="libp2p";var Yu=class extends Fr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let r=new Fr,n=r.dispatchEvent.bind(r);r.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new pa(a.type,{detail:a.detail}));return c||u},be(1/0,r),this.peerId=t.peerId,this.logger=t.logger??Do(),this.log=this.logger.forComponent("libp2p"),this.services={};let i=this.components=Qh({peerId:t.peerId,nodeInfo:t.nodeInfo??{name:Hd,version:$d},logger:this.logger,events:r,datastore:t.datastore??new Zo,connectionGater:od(t.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Qo(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),i.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Fs(this.components,{connectionEncryption:(t.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Ps(this.components,t.transportManager)),this.configureComponent("connectionManager",new Rs(this.components,t.connectionManager)),this.configureComponent("registrar",new Ds(this.components)),this.configureComponent("addressManager",new Jo(this.components,t.addresses));let o=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ls(this.components,{routers:o}));let s=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ts(this.components,{routers:s})),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",l=>{this.#t(l)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[ua]!=null&&(this.log("registering service %s for content routing",a),s.push(u[ua])),u[ha]!=null&&(this.log("registering service %s for peer routing",a),o.push(u[ha])),u[la]!=null&&(this.log("registering service %s for peer discovery",a),u[la].addEventListener?.("peer",l=>{this.#t(l)}))}}configureComponent(t,r){return r==null&&this.log.error("component %s was null or undefined",t),this.components[t]=r,r}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new we;for(let r of this.components.connectionManager.getConnections())t.add(r.remotePeer);return Array.from(t)}async dial(t,r={}){return this.components.connectionManager.openConnection(t,{priority:75,...r})}async dialProtocol(t,r,n={}){if(r==null)throw new A("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new A("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(t,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,r={}){Cr(t)&&(t=Dt(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,r)}async getPublicKey(t,r={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let o=await this.peerStore.get(t);if(o.id.publicKey!=null)return o.id.publicKey}catch(o){if(o.code!==F.ERR_NOT_FOUND)throw o}let n=Ct([Y("/pk/"),t.multihash.digest]),i=await this.contentRouting.get(n,r);return Si(i),await this.peerStore.patch(t,{publicKey:i}),i}async handle(t,r,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(t,r){return this.components.registrar.register(t,r)}unregister(t){this.components.registrar.unregister(t)}#t(t){let{detail:r}=t;if(r.id.toString()===this.peerId.toString()){this.log.error(new Error(F.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Gd(e={}){return e.peerId??=await uh(),new Yu(Bd(e))}async function zb(e={}){let t=await Gd(e);return e.start!==!1&&await t.start(),t}return sp($b);})();
|
|
32
40
|
/*! Bundled license information:
|
|
33
41
|
|
|
34
|
-
pvtsutils/build/index.js:
|
|
35
|
-
(*!
|
|
36
|
-
* MIT License
|
|
37
|
-
*
|
|
38
|
-
* Copyright (c) 2017-2022 Peculiar Ventures, LLC
|
|
39
|
-
*
|
|
40
|
-
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
41
|
-
* of this software and associated documentation files (the "Software"), to deal
|
|
42
|
-
* in the Software without restriction, including without limitation the rights
|
|
43
|
-
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
44
|
-
* copies of the Software, and to permit persons to whom the Software is
|
|
45
|
-
* furnished to do so, subject to the following conditions:
|
|
46
|
-
*
|
|
47
|
-
* The above copyright notice and this permission notice shall be included in all
|
|
48
|
-
* copies or substantial portions of the Software.
|
|
49
|
-
*
|
|
50
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
51
|
-
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
52
|
-
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
53
|
-
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
54
|
-
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
55
|
-
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
56
|
-
* SOFTWARE.
|
|
57
|
-
*
|
|
58
|
-
*)
|
|
59
|
-
|
|
60
42
|
@noble/hashes/esm/utils.js:
|
|
61
43
|
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
62
44
|
|
|
@@ -75,46 +57,6 @@ pvtsutils/build/index.js:
|
|
|
75
57
|
@noble/curves/esm/ed25519.js:
|
|
76
58
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
77
59
|
|
|
78
|
-
pvutils/build/utils.es.js:
|
|
79
|
-
(*!
|
|
80
|
-
Copyright (c) Peculiar Ventures, LLC
|
|
81
|
-
*)
|
|
82
|
-
|
|
83
|
-
asn1js/build/index.es.js:
|
|
84
|
-
(*!
|
|
85
|
-
* Copyright (c) 2014, GMO GlobalSign
|
|
86
|
-
* Copyright (c) 2015-2022, Peculiar Ventures
|
|
87
|
-
* All rights reserved.
|
|
88
|
-
*
|
|
89
|
-
* Author 2014-2019, Yury Strozhevsky
|
|
90
|
-
*
|
|
91
|
-
* Redistribution and use in source and binary forms, with or without modification,
|
|
92
|
-
* are permitted provided that the following conditions are met:
|
|
93
|
-
*
|
|
94
|
-
* * Redistributions of source code must retain the above copyright notice, this
|
|
95
|
-
* list of conditions and the following disclaimer.
|
|
96
|
-
*
|
|
97
|
-
* * Redistributions in binary form must reproduce the above copyright notice, this
|
|
98
|
-
* list of conditions and the following disclaimer in the documentation and/or
|
|
99
|
-
* other materials provided with the distribution.
|
|
100
|
-
*
|
|
101
|
-
* * Neither the name of the copyright holder nor the names of its
|
|
102
|
-
* contributors may be used to endorse or promote products derived from
|
|
103
|
-
* this software without specific prior written permission.
|
|
104
|
-
*
|
|
105
|
-
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
106
|
-
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
107
|
-
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
108
|
-
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
109
|
-
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
110
|
-
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
111
|
-
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
112
|
-
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
113
|
-
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
114
|
-
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
115
|
-
*
|
|
116
|
-
*)
|
|
117
|
-
|
|
118
60
|
@noble/curves/esm/abstract/weierstrass.js:
|
|
119
61
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
120
62
|
|