libp2p 2.1.2 → 2.1.3-a390db4a4

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 CHANGED
@@ -1,22 +1,22 @@
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 zp=Object.create;var To=Object.defineProperty;var Gp=Object.getOwnPropertyDescriptor;var Wp=Object.getOwnPropertyNames;var jp=Object.getPrototypeOf,Zp=Object.prototype.hasOwnProperty;var Qt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Rt=(r,t)=>{for(var e in t)To(r,e,{get:t[e],enumerable:!0})},Pu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wp(t))!Zp.call(r,o)&&o!==e&&To(r,o,{get:()=>t[o],enumerable:!(n=Gp(t,o))||n.enumerable});return r};var ir=(r,t,e)=>(e=r!=null?zp(jp(r)):{},Pu(t||!r||!r.__esModule?To(e,"default",{value:r,enumerable:!0}):e,r)),Xp=r=>Pu(To({},"__esModule",{value:!0}),r);var Uf=Qt(Zr=>{"use strict";var w0="[object ArrayBuffer]",Ce=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===w0}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);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(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},Kc="string",b0=/^[0-9a-f]+$/i,x0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v0=/^[a-zA-Z0-9-_]+$/,as=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Ce.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Zt=class{static toString(t,e=!1){let n=Ce.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},cs=class r{static isHex(t){return typeof t===Kc&&b0.test(t)}static isBase64(t){return typeof t===Kc&&x0.test(t)}static isBase64Url(t){return typeof t===Kc&&v0.test(t)}static ToString(t,e="utf8"){let n=Ce.toUint8Array(t);switch(e.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 Zt.toString(n,!0);case"utf16":case"utf16be":return Zt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Zt.fromString(t,!0);case"utf16":case"utf16be":return Zt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Ce.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return as.fromString(t);case"utf16":case"utf16be":return Zt.fromString(t);case"utf16le":case"usc2":return Zt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return as.toString(t);case"utf16":case"utf16be":return Zt.toString(t);case"utf16le":case"usc2":return Zt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Ce.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ce.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Zt.toString(t,e)}static FromUtf16String(t,e=!1){return Zt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};cs.DEFAULT_UTF8_ENCODING="utf8";function E0(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function A0(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function S0(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}Zr.BufferSourceConverter=Ce;Zr.Convert=cs;Zr.assign=E0;Zr.combine=A0;Zr.isEqual=S0});var yd=Qt(co=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],f=p[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")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,f,l,d,h;for(d=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)d=d*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+e(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;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(m){throw l=m,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,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),co.ip2long=i,co.long2ip=a,co.Netmask=r}).call(co)});var xd=Qt((lS,kl)=>{"use strict";var Cy=Object.prototype.hasOwnProperty,Vt="~";function lo(){}Object.create&&(lo.prototype=Object.create(null),new lo().__proto__||(Vt=!1));function Ty(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function bd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Ty(e,n||r,o),i=Vt?Vt+t:t;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 fi(r,t){--r._eventsCount===0?r._events=new lo:delete r._events[t]}function Nt(){this._events=new lo,this._eventsCount=0}Nt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Cy.call(e,n)&&t.push(Vt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Nt.prototype.listeners=function(t){var e=Vt?Vt+t:t,n=this._events[e];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};Nt.prototype.listenerCount=function(t){var e=Vt?Vt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(t,e,n,o,s,i){var a=Vt?Vt+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;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,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,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 d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(t,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,e);break;case 3:c[l].fn.call(c[l].context,e,n);break;case 4:c[l].fn.call(c[l].context,e,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};Nt.prototype.on=function(t,e,n){return bd(this,t,e,n,!1)};Nt.prototype.once=function(t,e,n){return bd(this,t,e,n,!0)};Nt.prototype.removeListener=function(t,e,n,o){var s=Vt?Vt+t:t;if(!this._events[s])return this;if(!e)return fi(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&fi(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:fi(this,s)}return this};Nt.prototype.removeAllListeners=function(t){var e;return t?(e=Vt?Vt+t:t,this._events[e]&&fi(this,e)):(this._events=new lo,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=Vt;Nt.EventEmitter=Nt;typeof kl<"u"&&(kl.exports=Nt)});var _d=Qt((NS,Sd)=>{Sd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Td=Qt((ZS,Cd)=>{"use strict";Cd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var Md=Qt((Rd,Dd)=>{"use strict";var mi=Td(),{hasOwnProperty:Nd}=Object.prototype,{propertyIsEnumerable:Dy}=Object,fn=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),My=Rd,Ld={concatArrays:!1,ignoreUndefined:!1},gi=r=>{let t=[];for(let e in r)Nd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)Dy.call(r,n)&&t.push(n)}return t};function hn(r){return Array.isArray(r)?Uy(r):mi(r)?Oy(r):r}function Uy(r){let t=r.slice(0,0);return gi(r).forEach(e=>{fn(t,e,hn(r[e]))}),t}function Oy(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return gi(r).forEach(e=>{fn(t,e,hn(r[e]))}),t}var Pd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?fn(r,o,Ml(r[o],t[o],n)):fn(r,o,hn(t[o])))}),r),Fy=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Nd.call(s,a)&&(i.push(String(a)),s===r?fn(n,o++,s[a]):fn(n,o++,hn(s[a])));n=Pd(n,s,gi(s).filter(a=>!i.includes(a)),e)}),n};function Ml(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?Fy(r,t,e):!mi(t)||!mi(r)?hn(t):Pd(r,t,gi(t),e)}Dd.exports=function(...r){let t=Ml(hn(Ld),this!==My&&this||{},Ld),e={_:{}};for(let n of r)if(n!==void 0){if(!mi(n))throw new TypeError("`"+n+"` is not an Option Object");e=Ml(e,{_:n},t)}return e._}});var Vd=Qt((po,Ai)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,x=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,x),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,x),y^=b}return y^=h.length,y=i(y),y>>>0},e.x86.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,x=p,A=0,_=0,v=0,B=0,T=597399067,et=2869860233,V=951274213,F=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,T),A=s(A,15),A=o(A,et),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,_=o(_,et),_=s(_,16),_=o(_,V),b^=_,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,V),v=s(v,17),v=o(v,F),w^=v,w=s(w,15),w+=x,w=o(w,5)+2530024501,B=o(B,F),B=s(B,18),B=o(B,T),x^=B,x=s(x,13),x+=y,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,F),B=s(B,18),B=o(B,T),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,V),v=s(v,17),v=o(v,F),w^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,et),_=s(_,16),_=o(_,V),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,T),A=s(A,15),A=o(A,et),y^=A}return y^=h.length,b^=h.length,w^=h.length,x^=h.length,y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,y=i(y),b=i(b),w=i(w),x=i(x),y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},e.x64.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],x=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[v+14]],48));case 14:x=l(x,f([0,h[v+13]],40));case 13:x=l(x,f([0,h[v+12]],32));case 12:x=l(x,f([0,h[v+11]],24));case 11:x=l(x,f([0,h[v+10]],16));case 10:x=l(x,f([0,h[v+9]],8));case 9:x=l(x,[0,h[v+8]]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof po<"u"?(typeof Ai<"u"&&Ai.exports&&(po=Ai.exports=e),po.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(po)});var $d=Qt((S8,Hd)=>{Hd.exports=Vd()});var Ep=Qt((cB,vp)=>{function Jt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}vp.exports=Jt;Jt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Jt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Jt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Jt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Jt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Jt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Jt.prototype.start=Jt.prototype.try;Jt.prototype.errors=function(){return this._errors};Jt.prototype.attempts=function(){return this._attempts};Jt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Ap=Qt(Cr=>{var Vw=Ep();Cr.operation=function(r){var t=Cr.timeouts(r);return new Vw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Cr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Cr.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Cr.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Cr.operation(t),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=t}}});var _p=Qt((uB,Sp)=>{Sp.exports=Ap()});var mb={};Rt(mb,{createLibp2p:()=>pb});var Ru=Symbol.for("@libp2p/connection");var Ta=Symbol.for("@libp2p/content-routing");var La=Symbol.for("@libp2p/peer-discovery");var Lo=Symbol.for("@libp2p/peer-id");function No(r){return!!r?.[Lo]}var Na=Symbol.for("@libp2p/peer-routing");var Pa="keep-alive";var Ab=Symbol.for("@libp2p/transport");var Fe;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Fe||(Fe={}));var be=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var D=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Nr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},Sn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Po=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Ro=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Do=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};var Pr=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Mo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Uo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},_n=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Oo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Fo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},xe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Rr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Dr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Vo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Ho=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Ve=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var tt=(r,...t)=>{try{[...t]}catch{}};var ve=class extends EventTarget{#t=new Map;constructor(){super(),tt(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function $o(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Du(...r){let t=[];for(let e of r)$o(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Mu(...r){let t=[];for(let e of r)$o(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Bn=Symbol.for("@libp2p/service-capabilities"),Ra=Symbol.for("@libp2p/service-dependencies");var Fa={};Rt(Fa,{base58btc:()=>W,base58flickr:()=>rm});var Qb=new Uint8Array(0);function Uu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ee(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 Ou(r){return new TextEncoder().encode(r)}function Fu(r){return new TextDecoder().decode(r)}function Yp(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[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(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,x=new Uint8Array(w);y!==b;){for(var A=p[y],_=0,v=w-1;(A!==0||_<g)&&v!==-1;v--,_++)A+=256*x[v]>>>0,x[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=_,y++}for(var B=w-g;B!==w&&x[B]===0;)B++;for(var T=c.repeat(m);B<w;++B)T+=r.charAt(x[B]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var x=e[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<y)&&_!==-1;_--,A++)x+=a*w[_]>>>0,w[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),T=g;v!==b;)B[T++]=w[v++];return B}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Jp=Yp,Qp=Jp,Hu=Qp;var Da=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ma=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 $u(this,t)}},Ua=class{decoders;constructor(t){this.decoders=t}or(t){return $u(this,t)}decode(t){let e=t[0],n=this.decoders[e];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 $u(r,t){return new Ua({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Oa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Da(t,e,n),this.decoder=new Ma(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Mr({name:r,prefix:t,encode:e,decode:n}){return new Oa(r,t,e,n)}function He({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Hu(e,r);return Mr({prefix:t,name:r,encode:n,decode:s=>Ee(o(s))})}function tm(r,t,e,n){let o={};for(let f=0;f<t.length;++f)o[t[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/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<<e|l,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function em(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Mr({prefix:t,name:r,encode(o){return em(o,n,e)},decode(o){return tm(o,n,e,r)}})}var W=He({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rm=He({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Va={};Rt(Va,{base32:()=>zt,base32hex:()=>im,base32hexpad:()=>cm,base32hexpadupper:()=>lm,base32hexupper:()=>am,base32pad:()=>om,base32padupper:()=>sm,base32upper:()=>nm,base32z:()=>um});var zt=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nm=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),om=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sm=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),im=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),am=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cm=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lm=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),um=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ha={};Rt(Ha,{base36:()=>In,base36upper:()=>fm});var In=He({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fm=He({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hm=zu,Ku=128,dm=127,pm=~dm,mm=Math.pow(2,31);function zu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=mm;)t[e++]=r&255|Ku,r/=128;for(;r&pm;)t[e++]=r&255|Ku,r>>>=7;return t[e]=r|0,zu.bytes=e-n+1,t}var gm=$a,ym=128,qu=127;function $a(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $a.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qu)<<o:(i&qu)*Math.pow(2,o),o+=7}while(i>=ym);return $a.bytes=s-n,e}var wm=Math.pow(2,7),bm=Math.pow(2,14),xm=Math.pow(2,21),vm=Math.pow(2,28),Em=Math.pow(2,35),Am=Math.pow(2,42),Sm=Math.pow(2,49),_m=Math.pow(2,56),Bm=Math.pow(2,63),Im=function(r){return r<wm?1:r<bm?2:r<xm?3:r<vm?4:r<Em?5:r<Am?6:r<Sm?7:r<_m?8:r<Bm?9:10},km={encode:hm,decode:gm,encodingLength:Im},Cm=km,kn=Cm;function Cn(r,t=0){return[kn.decode(r,t),kn.decode.bytes]}function Ur(r,t,e=0){return kn.encode(r,t,e),t}function Or(r){return kn.encodingLength(r)}function te(r,t){let e=t.byteLength,n=Or(r),o=n+Or(e),s=new Uint8Array(o+e);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),new Fr(r,e,t,s)}function ee(r){let t=Ee(r),[e,n]=Cn(t),[o,s]=Cn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Fr(e,o,i,t)}function Gu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Uu(r.bytes,e.bytes)}}var Fr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Wu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Lm(e,Ka(r),t??W.encoder);default:return Nm(e,Ka(r),t??zt.encoder)}}var ju=new WeakMap;function Ka(r){let t=ju.get(r);if(t==null){let e=new Map;return ju.set(r,e),e}return t}var pt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==Tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Pm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:e}=this.multihash,n=te(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Gu(t.multihash,n.multihash)}toString(t){return Wu(this,t)}toJSON(){return{"/":Wu(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 e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Zu(n,o,s.bytes))}else if(e[Rm]===!0){let{version:n,multihash:o,code:s}=e,i=ee(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="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(e!==Tn)throw new Error(`Version 0 CID must use dag-pb (code: ${Tn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Zu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Tn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Fr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=Cn(t.subarray(e));return e+=d,l},o=n(),s=Tn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=Tm(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ka(s).set(n,t),s}};function Tm(r,t){switch(r[0]){case"Q":{let e=t??W;return[W.prefix,e.decode(`${W.prefix}${r}`)]}case W.prefix:{let e=t??W;return[W.prefix,e.decode(r)]}case zt.prefix:{let e=t??zt;return[zt.prefix,e.decode(r)]}case In.prefix:{let e=t??In;return[In.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Lm(r,t,e){let{prefix:n}=e;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Nm(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Tn=112,Pm=18;function Zu(r,t,e){let n=Or(r),o=n+Or(t),s=new Uint8Array(o+e.byteLength);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),s}var Rm=Symbol.for("@ipld/js-cid/CID");var qa={};Rt(qa,{identity:()=>Se});var Xu=0,Dm="identity",Yu=Ee;function Mm(r){return te(Xu,Yu(r))}var Se={code:Xu,name:Dm,encode:Yu,digest:Mm};function it(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ju(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Um(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Vr(r,...t){if(!Um(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function Qu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ju(r.outputLen),Ju(r.blockLen)}function Hr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function tf(r,t){Vr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var qo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),re=(r,t)=>r<<32-t|r>>>t;var Ex=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Ln(r){return typeof r=="string"&&(r=ef(r)),Vr(r),r}function za(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Vr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var $r=class{clone(){return this._cloneInto()}},Ax={}.toString;function zo(r){let t=n=>r().update(Ln(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Kr(r=32){if(ar&&typeof ar.getRandomValues=="function")return ar.getRandomValues(new Uint8Array(r));if(ar&&typeof ar.randomBytes=="function")return ar.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Om(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var rf=(r,t,e)=>r&t^~r&e,nf=(r,t,e)=>r&t^r&e^t&e,qr=class extends $r{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=qo(this.buffer)}update(t){Hr(this);let{view:e,buffer:n,blockLen:o}=this;t=Ln(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=qo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Hr(this),tf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[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++)e[l]=0;Om(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=qo(t),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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Go=BigInt(4294967295),Ga=BigInt(32);function of(r,t=!1){return t?{h:Number(r&Go),l:Number(r>>Ga&Go)}:{h:Number(r>>Ga&Go)|0,l:Number(r&Go)|0}}function Fm(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=of(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Vm=(r,t)=>BigInt(r>>>0)<<Ga|BigInt(t>>>0),Hm=(r,t,e)=>r>>>e,$m=(r,t,e)=>r<<32-e|t>>>e,Km=(r,t,e)=>r>>>e|t<<32-e,qm=(r,t,e)=>r<<32-e|t>>>e,zm=(r,t,e)=>r<<64-e|t>>>e-32,Gm=(r,t,e)=>r>>>e-32|t<<64-e,Wm=(r,t)=>t,jm=(r,t)=>r,Zm=(r,t,e)=>r<<e|t>>>32-e,Xm=(r,t,e)=>t<<e|r>>>32-e,Ym=(r,t,e)=>t<<e-32|r>>>64-e,Jm=(r,t,e)=>r<<e-32|t>>>64-e;function Qm(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var tg=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),eg=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,rg=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ng=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,og=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),sg=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var ig={fromBig:of,split:Fm,toBig:Vm,shrSH:Hm,shrSL:$m,rotrSH:Km,rotrSL:qm,rotrBH:zm,rotrBL:Gm,rotr32H:Wm,rotr32L:jm,rotlSH:Zm,rotlSL:Xm,rotlBH:Ym,rotlBL:Jm,add:Qm,add3L:tg,add3H:eg,add4L:rg,add4H:ng,add5H:sg,add5L:og},O=ig;var[ag,cg]=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))),$e=new Uint32Array(80),Ke=new Uint32Array(80),Wa=class extends qr{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:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=t|0,this.Al=e|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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(t,e){for(let w=0;w<16;w++,e+=4)$e[w]=t.getUint32(e),Ke[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let x=$e[w-15]|0,A=Ke[w-15]|0,_=O.rotrSH(x,A,1)^O.rotrSH(x,A,8)^O.shrSH(x,A,7),v=O.rotrSL(x,A,1)^O.rotrSL(x,A,8)^O.shrSL(x,A,7),B=$e[w-2]|0,T=Ke[w-2]|0,et=O.rotrSH(B,T,19)^O.rotrBH(B,T,61)^O.shrSH(B,T,6),V=O.rotrSL(B,T,19)^O.rotrBL(B,T,61)^O.shrSL(B,T,6),F=O.add4L(v,V,Ke[w-7],Ke[w-16]),R=O.add4H(F,_,et,$e[w-7],$e[w-16]);$e[w]=R|0,Ke[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let x=O.rotrSH(l,d,14)^O.rotrSH(l,d,18)^O.rotrBH(l,d,41),A=O.rotrSL(l,d,14)^O.rotrSL(l,d,18)^O.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=O.add5L(b,A,v,cg[w],Ke[w]),T=O.add5H(B,y,x,_,ag[w],$e[w]),et=B|0,V=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),F=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),R=n&s^n&a^s&a,k=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=O.add(u|0,f|0,T|0,et|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=O.add3L(et,F,k);n=O.add3H(L,T,V,R),o=L|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:d}=O.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=O.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=O.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=O.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){$e.fill(0),Ke.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 sf=zo(()=>new Wa);var jo={};Rt(jo,{aInRange:()=>$t,abool:()=>ne,abytes:()=>zr,bitGet:()=>pg,bitLen:()=>Ja,bitMask:()=>Pn,bitSet:()=>mg,bytesToHex:()=>Be,bytesToNumberBE:()=>Ie,bytesToNumberLE:()=>ze,concatBytes:()=>ke,createHmacDrbg:()=>Qa,ensureBytes:()=>at,equalBytes:()=>hg,hexToBytes:()=>lr,hexToNumber:()=>Ya,inRange:()=>Nn,isBytes:()=>qe,memoized:()=>fr,notImplemented:()=>yg,numberToBytesBE:()=>Ge,numberToBytesLE:()=>ur,numberToHexUnpadded:()=>cr,numberToVarBytesBE:()=>fg,utf8ToBytes:()=>dg,validateObject:()=>ue});var Xa=BigInt(0),Wo=BigInt(1),lg=BigInt(2);function qe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function zr(r){if(!qe(r))throw new Error("Uint8Array expected")}function ne(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var ug=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Be(r){zr(r);let t="";for(let e=0;e<r.length;e++)t+=ug[r[e]];return t}function cr(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ya(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _e={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function af(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e._A&&r<=_e._F)return r-(_e._A-10);if(r>=_e._a&&r<=_e._f)return r-(_e._a-10)}function lr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=af(r.charCodeAt(s)),a=af(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 Ie(r){return Ya(Be(r))}function ze(r){return zr(r),Ya(Be(Uint8Array.from(r).reverse()))}function Ge(r,t){return lr(r.toString(16).padStart(t*2,"0"))}function ur(r,t){return Ge(r,t).reverse()}function fg(r){return lr(cr(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=lr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(qe(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function ke(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];zr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function hg(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function dg(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var ja=r=>typeof r=="bigint"&&Xa<=r;function Nn(r,t,e){return ja(r)&&ja(t)&&ja(e)&&t<=r&&r<e}function $t(r,t,e,n){if(!Nn(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function Ja(r){let t;for(t=0;r>Xa;r>>=Wo,t+=1);return t}function pg(r,t){return r>>BigInt(t)&Wo}function mg(r,t,e){return r|(e?Wo:Xa)<<BigInt(t)}var Pn=r=>(lg<<BigInt(r-1))-Wo,Za=r=>new Uint8Array(r),cf=r=>Uint8Array.from(r);function Qa(r,t,e){if(typeof r!="number"||r<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 e!="function")throw new Error("hmacFn must be a function");let n=Za(r),o=Za(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>e(o,n,...l),c=(l=Za())=>{o=a(cf([0]),l),n=a(),l.length!==0&&(o=a(cf([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<t;){n=a();let h=n.slice();d.push(h),l+=n.length}return ke(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var gg={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"||qe(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ue(r,t,e={}){let n=(o,s,i)=>{let a=gg[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(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var yg=()=>{throw new Error("not implemented")};function fr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var mt=BigInt(0),rt=BigInt(1),hr=BigInt(2),wg=BigInt(3),tc=BigInt(4),lf=BigInt(5),uf=BigInt(8),bg=BigInt(9),xg=BigInt(16);function Y(r,t){let e=r%t;return e>=mt?e:t+e}function vg(r,t,e){if(e<=mt||t<mt)throw new Error("Expected power/modulo > 0");if(e===rt)return mt;let n=rt;for(;t>mt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >mt;)n*=n,n%=e;return n}function Zo(r,t){if(r===mt||t<=mt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=Y(r,t),n=t,o=mt,s=rt,i=rt,a=mt;for(;e!==mt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==rt)throw new Error("invert: does not exist");return Y(o,t)}function Eg(r){let t=(r-rt)/hr,e,n,o;for(e=r-rt,n=0;e%hr===mt;e/=hr,n++);for(o=hr;o<r&&vg(o,t,r)!==r-rt;o++);if(n===1){let i=(r+rt)/tc;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=(e+rt)/hr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),e),l=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,rt<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function Ag(r){if(r%tc===wg){let t=(r+rt)/tc;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%uf===lf){let t=(r-lf)/uf;return function(n,o){let s=n.mul(o,hr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,hr),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%xg,Eg(r)}var ff=(r,t)=>(Y(r,t)&rt)===rt,Sg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ec(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Sg.reduce((n,o)=>(n[o]="function",n),t);return ue(r,e)}function _g(r,t,e){if(e<mt)throw new Error("Expected power > 0");if(e===mt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>mt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function Bg(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function rc(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function We(r,t,e=!1,n={}){if(r<=mt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=rc(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Ag(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Pn(o),ZERO:mt,ONE:rt,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return mt<=c&&c<r},is0:c=>c===mt,isOdd:c=>(c&rt)===rt,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>_g(a,c,u),div:(c,u)=>Y(c*Zo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Zo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Bg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>e?ur(c,s):Ge(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?ze(c):Ie(c)}});return Object.freeze(a)}function hf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function nc(r){let t=hf(r);return t+Math.ceil(t/2)}function df(r,t,e=!1){let n=r.length,o=hf(t),s=nc(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Ie(r):ze(r),a=Y(i,t-rt)+rt;return e?ur(a,o):Ge(a,o)}var kg=BigInt(0),oc=BigInt(1),sc=new WeakMap,pf=new WeakMap;function Xo(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>kg;)i&oc&&(a=a.add(c)),c=c.double(),i>>=oc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=oc);let b=g,w=g+Math.abs(y)-1,x=m%2!==0,A=y<0;y===0?l=l.add(e(x,i[b])):f=f.add(e(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=pf.get(s)||1,u=sc.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&sc.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),pf.set(s,i),sc.delete(s)}}}function Yo(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!t.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),e.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Ja(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(e[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function Rn(r){return ec(r.Fp),ue(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var oe=BigInt(0),Kt=BigInt(1),Jo=BigInt(2),Cg=BigInt(8),Tg={zip215:!0};function Lg(r){let t=Rn(r);return ue(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function mf(r){let t=Lg(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=Jo<<BigInt(a*8)-Kt,f=e.create,l=We(t.n,t.nBitLength),d=t.uvRatio||((S,E)=>{try{return{isValid:!0,value:e.sqrt(S*e.inv(E))}}catch{return{isValid:!1,value:oe}}}),h=t.adjustScalarBytes||(S=>S),p=t.domain||((S,E,I)=>{if(ne("phflag",I),E.length||I)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){$t("coordinate "+S,E,oe,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=fr((S,E)=>{let{ex:I,ey:N,ez:M}=S,U=S.is0();E==null&&(E=U?Cg:e.inv(M));let $=f(I*E),z=f(N*E),K=f(M*E);if(U)return{x:oe,y:Kt};if(K!==Kt)throw new Error("invZ was invalid");return{x:$,y:z}}),b=fr(S=>{let{a:E,d:I}=t;if(S.is0())throw new Error("bad point: ZERO");let{ex:N,ey:M,ez:U,et:$}=S,z=f(N*N),K=f(M*M),X=f(U*U),Q=f(X*X),bt=f(z*E),xt=f(X*f(bt+K)),Et=f(Q+f(I*f(z*K)));if(xt!==Et)throw new Error("bad point: equation left != right (1)");let Pt=f(N*M),dt=f(U*$);if(Pt!==dt)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,I,N,M){this.ex=E,this.ey=I,this.ez=N,this.et=M,m("x",E),m("y",I),m("z",N),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");let{x:I,y:N}=E||{};return m("x",I),m("y",N),new w(I,N,Kt,f(I*N))}static normalizeZ(E){let I=e.invertBatch(E.map(N=>N.ez));return E.map((N,M)=>N.toAffine(I[M])).map(w.fromAffine)}static msm(E,I){return Yo(w,l,E,I)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:I,ey:N,ez:M}=this,{ex:U,ey:$,ez:z}=E,K=f(I*z),X=f(U*M),Q=f(N*z),bt=f($*M);return K===X&&Q===bt}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=t,{ex:I,ey:N,ez:M}=this,U=f(I*I),$=f(N*N),z=f(Jo*f(M*M)),K=f(E*U),X=I+N,Q=f(f(X*X)-U-$),bt=K+$,xt=bt-z,Et=K-$,Pt=f(Q*xt),dt=f(bt*Et),Ht=f(Q*Et),we=f(xt*bt);return new w(Pt,dt,we,Ht)}add(E){g(E);let{a:I,d:N}=t,{ex:M,ey:U,ez:$,et:z}=this,{ex:K,ey:X,ez:Q,et:bt}=E;if(I===BigInt(-1)){let Bu=f((U-M)*(X+K)),Iu=f((U+M)*(X-K)),Ca=f(Iu-Bu);if(Ca===oe)return this.double();let ku=f($*Jo*bt),Cu=f(z*Jo*Q),Tu=Cu+ku,Lu=Iu+Bu,Nu=Cu-ku,Hp=f(Tu*Ca),$p=f(Lu*Nu),Kp=f(Tu*Nu),qp=f(Ca*Lu);return new w(Hp,$p,qp,Kp)}let xt=f(M*K),Et=f(U*X),Pt=f(z*N*bt),dt=f($*Q),Ht=f((M+U)*(K+X)-xt-Et),we=dt-Pt,En=dt+Pt,An=f(Et-I*xt),Up=f(Ht*we),Op=f(En*An),Fp=f(Ht*An),Vp=f(we*En);return new w(Up,Op,Vp,Fp)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){let I=E;$t("scalar",I,Kt,n);let{p:N,f:M}=this.wNAF(I);return w.normalizeZ([N,M])[0]}multiplyUnsafe(E){let I=E;return $t("scalar",I,oe,n),I===oe?A:this.equals(A)||I===Kt?this:this.equals(x)?this.wNAF(I).p:_.unsafeLadder(this,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return y(this,E)}clearCofactor(){let{h:E}=t;return E===Kt?this:this.multiplyUnsafe(E)}static fromHex(E,I=!1){let{d:N,a:M}=t,U=e.BYTES;E=at("pointHex",E,U),ne("zip215",I);let $=E.slice(),z=E[U-1];$[U-1]=z&-129;let K=ze($),X=I?u:e.ORDER;$t("pointHex.y",K,oe,X);let Q=f(K*K),bt=f(Q-Kt),xt=f(N*Q-M),{isValid:Et,value:Pt}=d(bt,xt);if(!Et)throw new Error("Point.fromHex: invalid y coordinate");let dt=(Pt&Kt)===Kt,Ht=(z&128)!==0;if(!I&&Pt===oe&&Ht)throw new Error("Point.fromHex: x=0 and x_0=1");return Ht!==dt&&(Pt=f(-Pt)),w.fromAffine({x:Pt,y:K})}static fromPrivateKey(E){return T(E).point}toRawBytes(){let{x:E,y:I}=this.toAffine(),N=ur(I,e.BYTES);return N[N.length-1]|=E&Kt?128:0,N}toHex(){return Be(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Kt,f(t.Gx*t.Gy)),w.ZERO=new w(oe,Kt,Kt,oe);let{BASE:x,ZERO:A}=w,_=Xo(w,a*8);function v(S){return Y(S,n)}function B(S){return v(ze(S))}function T(S){let E=a;S=at("private key",S,E);let I=at("hashed private key",s(S),2*E),N=h(I.slice(0,E)),M=I.slice(E,2*E),U=B(N),$=x.multiply(U),z=$.toRawBytes();return{head:N,prefix:M,scalar:U,point:$,pointBytes:z}}function et(S){return T(S).pointBytes}function V(S=new Uint8Array,...E){let I=ke(...E);return B(s(p(I,at("context",S),!!o)))}function F(S,E,I={}){S=at("message",S),o&&(S=o(S));let{prefix:N,scalar:M,pointBytes:U}=T(E),$=V(I.context,N,S),z=x.multiply($).toRawBytes(),K=V(I.context,z,U,S),X=v($+K*M);$t("signature.s",X,oe,n);let Q=ke(z,ur(X,e.BYTES));return at("result",Q,a*2)}let R=Tg;function k(S,E,I,N=R){let{context:M,zip215:U}=N,$=e.BYTES;S=at("signature",S,2*$),E=at("message",E),U!==void 0&&ne("zip215",U),o&&(E=o(E));let z=ze(S.slice($,2*$)),K,X,Q;try{K=w.fromHex(I,U),X=w.fromHex(S.slice(0,$),U),Q=x.multiplyUnsafe(z)}catch{return!1}if(!U&&K.isSmallOrder())return!1;let bt=V(M,X.toRawBytes(),K.toRawBytes(),E);return X.add(K.multiplyUnsafe(bt)).subtract(Q).clearCofactor().equals(w.ZERO)}return x._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:F,verify:k,ExtendedPoint:w,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(S=8,E=w.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var ic=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Gx=BigInt(0),Ng=BigInt(1),yf=BigInt(2),Wx=BigInt(3),Pg=BigInt(5),Rg=BigInt(8);function Dg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ic,a=r*r%s*r%s,c=nt(a,yf,s)*a%s,u=nt(c,Ng,s)*r%s,f=nt(u,Pg,s)*u%s,l=nt(f,t,s)*f%s,d=nt(l,e,s)*l%s,h=nt(d,n,s)*d%s,p=nt(h,o,s)*h%s,m=nt(p,o,s)*h%s,g=nt(m,t,s)*f%s;return{pow_p_5_8:nt(g,yf,s)*r%s,b2:a}}function Mg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Ug(r,t){let e=ic,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Dg(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*gf,e),f=a===r,l=a===Y(-r,e),d=a===Y(-r*gf,e);return f&&(i=c),(l||d)&&(i=u),ff(i,e)&&(i=Y(-i,e)),{isValid:f||l,value:i}}var Og=We(ic,void 0,!0),Fg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Og,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Rg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sf,randomBytes:Kr,adjustScalarBytes:Mg,uvRatio:Ug},Dn=mf(Fg);var Qo=32,ts=64,ac=32;function wf(){let r=Dn.utils.randomPrivateKey(),t=Dn.getPublicKey(r);return{privateKey:Vg(r,t),publicKey:t}}function bf(r,t){let e=r.subarray(0,ac);return Dn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function xf(r,t,e){return Dn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Vg(r,t){let e=new Uint8Array(ts);for(let n=0;n<ac;n++)e[n]=r[n],e[ac+n]=t[n];return e}var Mn=class{type="Ed25519";raw;constructor(t){this.raw=rs(t,Qo)}toMultihash(){return Se.digest(fe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return xf(this.raw,e,t)}},es=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=rs(t,ts),this.publicKey=new Mn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return bf(this.raw,t)}};function cc(r){return r=rs(r,Qo),new Mn(r)}async function Ef(){let{privateKey:r,publicKey:t}=wf();return new es(r,t)}function rs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function ct(r=0){return new Uint8Array(r)}function It(r=0){return new Uint8Array(r)}var Hg=Math.pow(2,7),$g=Math.pow(2,14),Kg=Math.pow(2,21),lc=Math.pow(2,28),uc=Math.pow(2,35),fc=Math.pow(2,42),hc=Math.pow(2,49),j=128,kt=127;function ht(r){if(r<Hg)return 1;if(r<$g)return 2;if(r<Kg)return 3;if(r<lc)return 4;if(r<uc)return 5;if(r<fc)return 6;if(r<hc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function dc(r,t,e=0){switch(ht(r)){case 8:t[e++]=r&255|j,r/=128;case 7:t[e++]=r&255|j,r/=128;case 6:t[e++]=r&255|j,r/=128;case 5:t[e++]=r&255|j,r/=128;case 4:t[e++]=r&255|j,r>>>=7;case 3:t[e++]=r&255|j,r>>>=7;case 2:t[e++]=r&255|j,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function qg(r,t,e=0){switch(ht(r)){case 8:t.set(e++,r&255|j),r/=128;case 7:t.set(e++,r&255|j),r/=128;case 6:t.set(e++,r&255|j),r/=128;case 5:t.set(e++,r&255|j),r/=128;case 4:t.set(e++,r&255|j),r>>>=7;case 3:t.set(e++,r&255|j),r>>>=7;case 2:t.set(e++,r&255|j),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function pc(r,t){let e=r[t],n=0;if(n+=e&kt,e<j||(e=r[t+1],n+=(e&kt)<<7,e<j)||(e=r[t+2],n+=(e&kt)<<14,e<j)||(e=r[t+3],n+=(e&kt)<<21,e<j)||(e=r[t+4],n+=(e&kt)*lc,e<j)||(e=r[t+5],n+=(e&kt)*uc,e<j)||(e=r[t+6],n+=(e&kt)*fc,e<j)||(e=r[t+7],n+=(e&kt)*hc,e<j))return n;throw new RangeError("Could not decode varint")}function zg(r,t){let e=r.get(t),n=0;if(n+=e&kt,e<j||(e=r.get(t+1),n+=(e&kt)<<7,e<j)||(e=r.get(t+2),n+=(e&kt)<<14,e<j)||(e=r.get(t+3),n+=(e&kt)<<21,e<j)||(e=r.get(t+4),n+=(e&kt)*lc,e<j)||(e=r.get(t+5),n+=(e&kt)*uc,e<j)||(e=r.get(t+6),n+=(e&kt)*fc,e<j)||(e=r.get(t+7),n+=(e&kt)*hc,e<j))return n;throw new RangeError("Could not decode varint")}function Ct(r,t,e=0){return t==null&&(t=It(ht(r))),t instanceof Uint8Array?dc(r,t,e):qg(r,t,e)}function se(r,t=0){return r instanceof Uint8Array?pc(r,t):zg(r,t)}var mc=new Float32Array([-0]),je=new Uint8Array(mc.buffer);function Af(r,t,e){mc[0]=r,t[e]=je[0],t[e+1]=je[1],t[e+2]=je[2],t[e+3]=je[3]}function Sf(r,t){return je[0]=r[t],je[1]=r[t+1],je[2]=r[t+2],je[3]=r[t+3],mc[0]}var gc=new Float64Array([-0]),Tt=new Uint8Array(gc.buffer);function _f(r,t,e){gc[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Bf(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],gc[0]}var Gg=BigInt(Number.MAX_SAFE_INTEGER),Wg=BigInt(Number.MIN_SAFE_INTEGER),Gt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+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 e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(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,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return pr;if(t<Gg&&t>Wg)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>If&&(o=0n,++n>If&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return pr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):pr}},pr=new Gt(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var If=4294967296n;function kf(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Cf(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 yc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ie(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ns(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var wc=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,ie(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 ie(this,4);return ns(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ie(this,4);return ns(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ie(this,4);let t=Sf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ie(this,4);let t=Bf(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ie(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Cf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ie(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ie(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 Gt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*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;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ie(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ie(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ie(this,8);let t=ns(this.buf,this.pos+=4),e=ns(this.buf,this.pos+=4);return new Gt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=pc(this.buf,this.pos);return this.pos+=ht(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function bc(r){return new wc(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=bc(r);return t.decode(n,void 0,e)}var xc={};Rt(xc,{base10:()=>jg});var jg=He({prefix:"9",name:"base10",alphabet:"0123456789"});var vc={};Rt(vc,{base16:()=>Zg,base16upper:()=>Xg});var Zg=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xg=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ec={};Rt(Ec,{base2:()=>Yg});var Yg=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ac={};Rt(Ac,{base256emoji:()=>r0});var Lf=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}"),Jg=Lf.reduce((r,t,e)=>(r[e]=t,r),[]),Qg=Lf.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function t0(r){return r.reduce((t,e)=>(t+=Jg[e],t),"")}function e0(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Qg[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var r0=Mr({prefix:"\u{1F680}",name:"base256emoji",encode:t0,decode:e0});var Bc={};Rt(Bc,{base64:()=>Sc,base64pad:()=>n0,base64url:()=>_c,base64urlpad:()=>o0});var Sc=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),n0=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_c=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o0=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ic={};Rt(Ic,{base8:()=>s0});var s0=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var kc={};Rt(kc,{identity:()=>i0});var i0=Mr({prefix:"\0",name:"identity",encode:r=>Fu(r),decode:r=>Ou(r)});var B1=new TextEncoder,I1=new TextDecoder;var Lc={};Rt(Lc,{sha256:()=>Gr,sha512:()=>l0});function Tc({name:r,code:t,encode:e}){return new Cc(r,t,e)}var Cc=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?te(this.code,e):e.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pf(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Gr=Tc({name:"sha2-256",code:18,encode:Pf("SHA-256")}),l0=Tc({name:"sha2-512",code:19,encode:Pf("SHA-512")});var Un={...kc,...Ec,...Ic,...xc,...vc,...Va,...Ha,...Fa,...Bc,...Ac},F1={...Lc,...qa};function Df(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Rf=Df("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Nc=Df("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=It(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),u0={utf8:Rf,"utf-8":Rf,hex:Un.base16,latin1:Nc,ascii:Nc,binary:Nc,...Un},os=u0;function P(r,t="utf8"){let e=os[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Pc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return It(i);o+i>t&&(n=It(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Rc(){}var Mc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},f0=Pc();function h0(r){return globalThis.Buffer!=null?It(r):f0(r)}var Fn=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(Rc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new mr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Uc((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(ss,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(ss,e.length(),e)}uint64Number(t){return this._push(dc,ht(t),t)}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 e=Gt.fromBigInt(t).zzEncode();return this._push(ss,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(ss,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Dc,1,t?1:0)}fixed32(t){return this._push(On,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(On,4,e.lo)._push(On,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(On,4,e.lo)._push(On,4,e.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(Af,4,t)}double(t){return this._push(_f,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Dc,1,0):this.uint32(e)._push(p0,e,t)}string(t){let e=kf(t);return e!==0?this.uint32(e)._push(yc,e,t):this._push(Dc,1,0)}fork(){return this.states=new Mc(this),this.head=this.tail=new mr(Rc,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 mr(Rc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=h0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Dc(r,t,e){t[e]=r&255}function d0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Uc=class extends mr{next;constructor(t,e){super(d0,t,e),this.next=void 0}};function ss(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function On(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function p0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Fn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(m0,t,r),this},Fn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(g0,t,r),this});function m0(r,t,e){t.set(r,e)}function g0(r,t,e){r.length<40?yc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function Oc(){return new Fn}function Mt(r,t){let e=Oc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Wr;(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"})(Wr||(Wr={}));function is(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Fc(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return is("enum",Wr.VARINT,e,n)}function Ut(r,t){return is("message",Wr.LENGTH_DELIMITED,r,t)}var gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Vn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var gt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(gt||(gt={}));var Vc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(Vc||(Vc={}));(function(r){r.codec=()=>Fc(Vc)})(gt||(gt={}));var he;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),gt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=gt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(he||(he={}));var Hc;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),gt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=gt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Hc||(Hc={}));var Yn={};Rt(Yn,{MAX_RSA_KEY_SIZE:()=>Ys,generateRSAKeyPair:()=>Jc,jwkToJWKKeyPair:()=>Nh,jwkToPkcs1:()=>N0,jwkToPkix:()=>Xc,jwkToRSAPrivateKey:()=>Lh,pkcs1ToJwk:()=>kh,pkcs1ToRSAPrivateKey:()=>Th,pkixToJwk:()=>Ch,pkixToRSAPublicKey:()=>Yc});var y0=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]),Ze=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xe=new Uint32Array(64),$c=class extends qr{constructor(){super(64,32,8,!1),this.A=Ze[0]|0,this.B=Ze[1]|0,this.C=Ze[2]|0,this.D=Ze[3]|0,this.E=Ze[4]|0,this.F=Ze[5]|0,this.G=Ze[6]|0,this.H=Ze[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|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(t,e){for(let l=0;l<16;l++,e+=4)Xe[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Xe[l-15],h=Xe[l-2],p=re(d,7)^re(d,18)^d>>>3,m=re(h,17)^re(h,19)^h>>>10;Xe[l]=m+Xe[l-7]+p+Xe[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 d=re(a,6)^re(a,11)^re(a,25),h=f+d+rf(a,c,u)+y0[l]+Xe[l]|0,m=(re(n,2)^re(n,13)^re(n,22))+nf(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|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(){Xe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var jr=zo(()=>new $c);var q=ir(Uf());function yr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Ye(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);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*t);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function ls(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function qc(){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 t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=yr(e,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,yr(s,8)-n}function Of(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=Ye(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ye(t,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}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ff(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function qt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var xv=Math.log(2);function us(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function zc(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Pe(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-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 $n=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return zc(this.items)}},Hn=[new Uint8Array([1])],Vf="0123456789";var Qr="",ae=new ArrayBuffer(0),Gc=new Uint8Array(0),Kn="EndOfContent",$f="OCTET STRING",Kf="BIT STRING";function Re(r){var t;return t=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?q.BufferSourceConverter.toUint8Array(s.valueHex):Gc}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(!Pe(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",ae)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Te=class{constructor({blockLength:t=0,error:e=Qr,warnings:n=[],valueBeforeDecode:o=Gc}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Te.NAME="baseBlock";var Lt=class extends Te{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var fs=class extends Re(Te){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?q.BufferSourceConverter.toUint8Array(t.valueHex):Gc,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",ae}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Ye(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){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]=e|31,!t){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(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+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 d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[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 d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=yr(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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};fs.NAME="identificationBlock";var hs=class extends Te{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+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,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+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=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=yr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Ye(this.length,8);if(o.byteLength>127)return this.error="Too big length",ae;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};hs.NAME="lengthBlock";var C={},At=class extends Te{constructor({name:t=Qr,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new fs(o),this.lenBlock=new hs(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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(t,e){let n=e||new $n;e||qf(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?ae:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Ff(e,n)}};At.NAME="BaseBlock";function qf(r){if(r instanceof C.Constructed)for(let t of r.valueBlock.value)qf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ds=class extends At{constructor({value:t=Qr,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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}'`}};ds.NAME="BaseStringBlock";var ps=class extends Re(Lt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};ps.NAME="PrimitiveValueBlock";var zf,ms=class extends At{constructor(t={}){super(t,ps),this.idBlock.isConstructed=!1}};zf=ms;C.Primitive=zf;ms.NAME="PRIMITIVE";function B0(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Zs(r,t=0,e=r.length){let n=t,o=new At({},Lt),s=new Te;if(!Pe(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=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=At;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=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.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?C.Constructed:C.Primitive}return o=B0(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Wc(r){if(!r.byteLength){let t=new At({},Lt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Zs(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function I0(r,t){return r?1:t}var de=class extends Lt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;I0(this.isIndefiniteForm,n)>0;){let i=Zs(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===Kn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Kn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new $n;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ae:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};de.NAME="ConstructedValueBlock";var Gf,Je=class extends At{constructor(t={}){super(t,de),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,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 t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
2
+ "use strict";var Libp2P=(()=>{var Gp=Object.create;var Lo=Object.defineProperty;var Wp=Object.getOwnPropertyDescriptor;var jp=Object.getOwnPropertyNames;var Zp=Object.getPrototypeOf,Xp=Object.prototype.hasOwnProperty;var Qe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Re=(r,e)=>{for(var t in e)Lo(r,t,{get:e[t],enumerable:!0})},Mu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jp(e))!Xp.call(r,o)&&o!==t&&Lo(r,o,{get:()=>e[o],enumerable:!(n=Wp(e,o))||n.enumerable});return r};var ar=(r,e,t)=>(t=r!=null?Gp(Zp(r)):{},Mu(e||!r||!r.__esModule?Lo(t,"default",{value:r,enumerable:!0}):t,r)),Yp=r=>Mu(Lo({},"__esModule",{value:!0}),r);var Vf=Qe(Xr=>{"use strict";var b0="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===b0}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}},Wc="string",x0=/^[0-9a-f]+$/i,v0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,E0=/^[a-zA-Z0-9-_]+$/,cs=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))}},Xe=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}},ls=class r{static isHex(e){return typeof e===Wc&&x0.test(e)}static isBase64(e){return typeof e===Wc&&v0.test(e)}static isBase64Url(e){return typeof e===Wc&&E0.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 Xe.toString(n,!0);case"utf16":case"utf16be":return Xe.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 Xe.fromString(e,!0);case"utf16":case"utf16be":return Xe.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 cs.fromString(e);case"utf16":case"utf16be":return Xe.fromString(e);case"utf16le":case"usc2":return Xe.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 cs.toString(e);case"utf16":case"utf16be":return Xe.toString(e);case"utf16le":case"usc2":return Xe.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 Xe.toString(e,t)}static FromUtf16String(e,t=!1){return Xe.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,"")||""}};ls.DEFAULT_UTF8_ENCODING="utf8";function A0(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 S0(...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 _0(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}Xr.BufferSourceConverter=kt;Xr.Convert=ls;Xr.assign=A0;Xr.combine=S0;Xr.isEqual=_0});var wd=Qe(uo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[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,d,h;for(d=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)d=d*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;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(m){throw l=m,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,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),uo.ip2long=i,uo.long2ip=a,uo.Netmask=r}).call(uo)});var vd=Qe((uS,Ll)=>{"use strict";var Ty=Object.prototype.hasOwnProperty,Ve="~";function fo(){}Object.create&&(fo.prototype=Object.create(null),new fo().__proto__||(Ve=!1));function Ly(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function xd(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Ly(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 mi(r,e){--r._eventsCount===0?r._events=new fo:delete r._events[e]}function Ne(){this._events=new fo,this._eventsCount=0}Ne.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ty.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ne.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};Ne.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ne.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 d=c.length,h;for(l=0;l<d;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};Ne.prototype.on=function(e,t,n){return xd(this,e,t,n,!1)};Ne.prototype.once=function(e,t,n){return xd(this,e,t,n,!0)};Ne.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return mi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&mi(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:mi(this,s)}return this};Ne.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&mi(this,t)):(this._events=new fo,this._eventsCount=0),this};Ne.prototype.off=Ne.prototype.removeListener;Ne.prototype.addListener=Ne.prototype.on;Ne.prefixed=Ve;Ne.EventEmitter=Ne;typeof Ll<"u"&&(Ll.exports=Ne)});var Bd=Qe((PS,_d)=>{_d.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Ld=Qe((XS,Td)=>{"use strict";Td.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Ud=Qe((Dd,Md)=>{"use strict";var bi=Ld(),{hasOwnProperty:Pd}=Object.prototype,{propertyIsEnumerable:My}=Object,hn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Uy=Dd,Nd={concatArrays:!1,ignoreUndefined:!1},xi=r=>{let e=[];for(let t in r)Pd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)My.call(r,n)&&e.push(n)}return e};function dn(r){return Array.isArray(r)?Oy(r):bi(r)?Fy(r):r}function Oy(r){let e=r.slice(0,0);return xi(r).forEach(t=>{hn(e,t,dn(r[t]))}),e}function Fy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return xi(r).forEach(t=>{hn(e,t,dn(r[t]))}),e}var Rd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?hn(r,o,Fl(r[o],e[o],n)):hn(r,o,dn(e[o])))}),r),Vy=(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++)Pd.call(s,a)&&(i.push(String(a)),s===r?hn(n,o++,s[a]):hn(n,o++,dn(s[a])));n=Rd(n,s,xi(s).filter(a=>!i.includes(a)),t)}),n};function Fl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Vy(r,e,t):!bi(e)||!bi(r)?dn(e):Rd(r,e,xi(e),t)}Md.exports=function(...r){let e=Fl(dn(Nd),this!==Uy&&this||{},Nd),t={_:{}};for(let n of r)if(n!==void 0){if(!bi(n))throw new TypeError("`"+n+"` is not an Option Object");t=Fl(t,{_:n},e)}return t._}});var Hd=Qe((go,Ii)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,x=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,x),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,x),y^=b}return y^=h.length,y=i(y),y>>>0},t.x86.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,x=p,A=0,_=0,v=0,B=0,T=597399067,re=2869860233,V=951274213,F=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,T),A=s(A,15),A=o(A,re),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,_=o(_,re),_=s(_,16),_=o(_,V),b^=_,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,V),v=s(v,17),v=o(v,F),w^=v,w=s(w,15),w+=x,w=o(w,5)+2530024501,B=o(B,F),B=s(B,18),B=o(B,T),x^=B,x=s(x,13),x+=y,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,F),B=s(B,18),B=o(B,T),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,V),v=s(v,17),v=o(v,F),w^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,re),_=s(_,16),_=o(_,V),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,T),A=s(A,15),A=o(A,re),y^=A}return y^=h.length,b^=h.length,w^=h.length,x^=h.length,y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,y=i(y),b=i(b),w=i(w),x=i(x),y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],x=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[v+14]],48));case 14:x=l(x,f([0,h[v+13]],40));case 13:x=l(x,f([0,h[v+12]],32));case 12:x=l(x,f([0,h[v+11]],24));case 11:x=l(x,f([0,h[v+10]],16));case 10:x=l(x,f([0,h[v+9]],8));case 9:x=l(x,[0,h[v+8]]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof go<"u"?(typeof Ii<"u"&&Ii.exports&&(go=Ii.exports=t),go.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(go)});var Kd=Qe((_8,$d)=>{$d.exports=Hd()});var Ap=Qe((lB,Ep)=>{function Je(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Ep.exports=Je;Je.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Je.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Je.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Je.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Je.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Je.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Je.prototype.start=Je.prototype.try;Je.prototype.errors=function(){return this._errors};Je.prototype.attempts=function(){return this._attempts};Je.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=t&&(e=o,t=i)}return e}});var Sp=Qe(Lr=>{var Hw=Ap();Lr.operation=function(r){var e=Lr.timeouts(r);return new Hw(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Lr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<e.retries;o++)n.push(this.createTimeout(o,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,e)),n.sort(function(s,i){return s-i}),n};Lr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Lr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var o=0;o<t.length;o++){var s=t[o],i=r[s];r[s]=function(c){var u=Lr.operation(e),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=e}}});var Bp=Qe((fB,_p)=>{_p.exports=Sp()});var gb={};Re(gb,{createLibp2p:()=>mb});var Uu=Symbol.for("@libp2p/connection");var Ra=Symbol.for("@libp2p/content-routing");var Da=Symbol.for("@libp2p/peer-discovery");var No=Symbol.for("@libp2p/peer-id");function Po(r){return!!r?.[No]}var Ma=Symbol.for("@libp2p/peer-routing");var Ua="keep-alive";var Sb=Symbol.for("@libp2p/transport");var Ft;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ft||(Ft={}));var et=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var D=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Rr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},_n=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Ro=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Do=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Mo=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Bn=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Vt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Uo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Oo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},In=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Fo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Vo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},bt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Dr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Mr=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ho=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},$o=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ht=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ee=(r,...e)=>{try{[...e]}catch{}};var xt=class extends EventTarget{#e=new Map;constructor(){super(),ee(1/0,this)}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 CustomEvent(e,t))}};function Ko(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ou(...r){let e=[];for(let t of r)Ko(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Fu(...r){let e=[];for(let t of r)Ko(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var kn=Symbol.for("@libp2p/service-capabilities"),Oa=Symbol.for("@libp2p/service-dependencies");var Ka={};Re(Ka,{base58btc:()=>W,base58flickr:()=>nm});var ex=new Uint8Array(0);function Vu(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 vt(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 Hu(r){return new TextEncoder().encode(r)}function $u(r){return new TextDecoder().decode(r)}function Jp(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(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,x=new Uint8Array(w);y!==b;){for(var A=p[y],_=0,v=w-1;(A!==0||_<g)&&v!==-1;v--,_++)A+=256*x[v]>>>0,x[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=_,y++}for(var B=w-g;B!==w&&x[B]===0;)B++;for(var T=c.repeat(m);B<w;++B)T+=r.charAt(x[B]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<y)&&_!==-1;_--,A++)x+=a*w[_]>>>0,w[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),T=g;v!==b;)B[T++]=w[v++];return B}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Qp=Jp,em=Qp,qu=em;var Fa=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")}},Va=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 zu(this,e)}},Ha=class{decoders;constructor(e){this.decoders=e}or(e){return zu(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 zu(r,e){return new Ha({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var $a=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 Fa(e,t,n),this.decoder=new Va(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ur({name:r,prefix:e,encode:t,decode:n}){return new $a(r,e,t,n)}function $t({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=qu(t,r);return Ur({prefix:e,name:r,encode:n,decode:s=>vt(o(s))})}function tm(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 rm(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 ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Ur({prefix:e,name:r,encode(o){return rm(o,n,t)},decode(o){return tm(o,n,t,r)}})}var W=$t({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nm=$t({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qa={};Re(qa,{base32:()=>We,base32hex:()=>am,base32hexpad:()=>lm,base32hexpadupper:()=>um,base32hexupper:()=>cm,base32pad:()=>sm,base32padupper:()=>im,base32upper:()=>om,base32z:()=>fm});var We=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),om=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sm=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),im=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),am=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),cm=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),lm=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),um=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fm=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var za={};Re(za,{base36:()=>Cn,base36upper:()=>hm});var Cn=$t({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hm=$t({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var dm=ju,Gu=128,pm=127,mm=~pm,gm=Math.pow(2,31);function ju(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gm;)e[t++]=r&255|Gu,r/=128;for(;r&mm;)e[t++]=r&255|Gu,r>>>=7;return e[t]=r|0,ju.bytes=t-n+1,e}var ym=Ga,wm=128,Wu=127;function Ga(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ga.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Wu)<<o:(i&Wu)*Math.pow(2,o),o+=7}while(i>=wm);return Ga.bytes=s-n,t}var bm=Math.pow(2,7),xm=Math.pow(2,14),vm=Math.pow(2,21),Em=Math.pow(2,28),Am=Math.pow(2,35),Sm=Math.pow(2,42),_m=Math.pow(2,49),Bm=Math.pow(2,56),Im=Math.pow(2,63),km=function(r){return r<bm?1:r<xm?2:r<vm?3:r<Em?4:r<Am?5:r<Sm?6:r<_m?7:r<Bm?8:r<Im?9:10},Cm={encode:dm,decode:ym,encodingLength:km},Tm=Cm,Tn=Tm;function Ln(r,e=0){return[Tn.decode(r,e),Tn.decode.bytes]}function Or(r,e,t=0){return Tn.encode(r,e,t),e}function Fr(r){return Tn.encodingLength(r)}function tt(r,e){let t=e.byteLength,n=Fr(r),o=n+Fr(t),s=new Uint8Array(o+t);return Or(r,s,0),Or(t,s,n),s.set(e,o),new Vr(r,t,e,s)}function rt(r){let e=vt(r),[t,n]=Ln(e),[o,s]=Ln(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Vr(t,o,i,e)}function Zu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Vu(r.bytes,t.bytes)}}var Vr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Xu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Nm(t,Wa(r),e??W.encoder);default:return Pm(t,Wa(r),e??We.encoder)}}var Yu=new WeakMap;function Wa(r){let e=Yu.get(r);if(e==null){let t=new Map;return Yu.set(r,t),t}return e}var ge=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!==Nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Rm)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=tt(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&&Zu(e.multihash,n.multihash)}toString(e){return Xu(this,e)}toJSON(){return{"/":Xu(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??Ju(n,o,s.bytes))}else if(t[Dm]===!0){let{version:n,multihash:o,code:s}=t,i=rt(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!==Nn)throw new Error(`Version 0 CID must use dag-pb (code: ${Nn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Ju(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Nn,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=vt(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 Vr(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,d]=Ln(e.subarray(t));return t+=d,l},o=n(),s=Nn;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]=Lm(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 Wa(s).set(n,e),s}};function Lm(r,e){switch(r[0]){case"Q":{let t=e??W;return[W.prefix,t.decode(`${W.prefix}${r}`)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Cn.prefix:{let t=e??Cn;return[Cn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Nm(r,e,t){let{prefix:n}=t;if(n!==W.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 Pm(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 Nn=112,Rm=18;function Ju(r,e,t){let n=Fr(r),o=n+Fr(e),s=new Uint8Array(o+t.byteLength);return Or(r,s,0),Or(e,s,n),s.set(t,o),s}var Dm=Symbol.for("@ipld/js-cid/CID");var ja={};Re(ja,{identity:()=>At});var Qu=0,Mm="identity",ef=vt;function Um(r){return tt(Qu,ef(r))}var At={code:Qu,name:Mm,encode:ef,digest:Um};function ce(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 tf(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Om(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Hr(r,...e){if(!Om(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function rf(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");tf(r.outputLen),tf(r.blockLen)}function $r(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 nf(r,e){Hr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var cr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var zo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),nt=(r,e)=>r<<32-e|r>>>e;var Ax=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function of(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Pn(r){return typeof r=="string"&&(r=of(r)),Hr(r),r}function Za(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Hr(o),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 Kr=class{clone(){return this._cloneInto()}},Sx={}.toString;function Go(r){let e=n=>r().update(Pn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function qr(r=32){if(cr&&typeof cr.getRandomValues=="function")return cr.getRandomValues(new Uint8Array(r));if(cr&&typeof cr.randomBytes=="function")return cr.randomBytes(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 sf=(r,e,t)=>r&e^~r&t,af=(r,e,t)=>r&e^r&t^e&t,zr=class extends Kr{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=zo(this.buffer)}update(e){$r(this);let{view:t,buffer:n,blockLen:o}=this;e=Pn(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=zo(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){$r(this),nf(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=zo(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 Wo=BigInt(4294967295),Xa=BigInt(32);function cf(r,e=!1){return e?{h:Number(r&Wo),l:Number(r>>Xa&Wo)}:{h:Number(r>>Xa&Wo)|0,l:Number(r&Wo)|0}}function Vm(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}=cf(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Hm=(r,e)=>BigInt(r>>>0)<<Xa|BigInt(e>>>0),$m=(r,e,t)=>r>>>t,Km=(r,e,t)=>r<<32-t|e>>>t,qm=(r,e,t)=>r>>>t|e<<32-t,zm=(r,e,t)=>r<<32-t|e>>>t,Gm=(r,e,t)=>r<<64-t|e>>>t-32,Wm=(r,e,t)=>r>>>t-32|e<<64-t,jm=(r,e)=>e,Zm=(r,e)=>r,Xm=(r,e,t)=>r<<t|e>>>32-t,Ym=(r,e,t)=>e<<t|r>>>32-t,Jm=(r,e,t)=>e<<t-32|r>>>64-t,Qm=(r,e,t)=>r<<t-32|e>>>64-t;function eg(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var tg=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),rg=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,ng=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),og=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,sg=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),ig=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var ag={fromBig:cf,split:Vm,toBig:Hm,shrSH:$m,shrSL:Km,rotrSH:qm,rotrSL:zm,rotrBH:Gm,rotrBL:Wm,rotr32H:jm,rotr32L:Zm,rotlSH:Xm,rotlSL:Ym,rotlBH:Jm,rotlBL:Qm,add:eg,add3L:tg,add3H:rg,add4L:ng,add4H:og,add5H:ig,add5L:sg},O=ag;var[cg,lg]=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))),Kt=new Uint32Array(80),qt=new Uint32Array(80),Ya=class extends zr{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:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)Kt[w]=e.getUint32(t),qt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=Kt[w-15]|0,A=qt[w-15]|0,_=O.rotrSH(x,A,1)^O.rotrSH(x,A,8)^O.shrSH(x,A,7),v=O.rotrSL(x,A,1)^O.rotrSL(x,A,8)^O.shrSL(x,A,7),B=Kt[w-2]|0,T=qt[w-2]|0,re=O.rotrSH(B,T,19)^O.rotrBH(B,T,61)^O.shrSH(B,T,6),V=O.rotrSL(B,T,19)^O.rotrBL(B,T,61)^O.shrSL(B,T,6),F=O.add4L(v,V,qt[w-7],qt[w-16]),R=O.add4H(F,_,re,Kt[w-7],Kt[w-16]);Kt[w]=R|0,qt[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let x=O.rotrSH(l,d,14)^O.rotrSH(l,d,18)^O.rotrBH(l,d,41),A=O.rotrSL(l,d,14)^O.rotrSL(l,d,18)^O.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=O.add5L(b,A,v,lg[w],qt[w]),T=O.add5H(B,y,x,_,cg[w],Kt[w]),re=B|0,V=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),F=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),R=n&s^n&a^s&a,k=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=O.add(u|0,f|0,T|0,re|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=O.add3L(re,F,k);n=O.add3H(L,T,V,R),o=L|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:d}=O.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=O.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=O.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=O.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){Kt.fill(0),qt.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 lf=Go(()=>new Ya);var Zo={};Re(Zo,{aInRange:()=>$e,abool:()=>ot,abytes:()=>Gr,bitGet:()=>mg,bitLen:()=>rc,bitMask:()=>Dn,bitSet:()=>gg,bytesToHex:()=>_t,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Gt,concatBytes:()=>It,createHmacDrbg:()=>nc,ensureBytes:()=>le,equalBytes:()=>dg,hexToBytes:()=>ur,hexToNumber:()=>tc,inRange:()=>Rn,isBytes:()=>zt,memoized:()=>hr,notImplemented:()=>wg,numberToBytesBE:()=>Wt,numberToBytesLE:()=>fr,numberToHexUnpadded:()=>lr,numberToVarBytesBE:()=>hg,utf8ToBytes:()=>pg,validateObject:()=>ft});var ec=BigInt(0),jo=BigInt(1),ug=BigInt(2);function zt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r){if(!zt(r))throw new Error("Uint8Array expected")}function ot(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var fg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function _t(r){Gr(r);let e="";for(let t=0;t<r.length;t++)e+=fg[r[t]];return e}function lr(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function tc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var St={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function uf(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St._A&&r<=St._F)return r-(St._A-10);if(r>=St._a&&r<=St._f)return r-(St._a-10)}function ur(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=uf(r.charCodeAt(s)),a=uf(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 tc(_t(r))}function Gt(r){return Gr(r),tc(_t(Uint8Array.from(r).reverse()))}function Wt(r,e){return ur(r.toString(16).padStart(e*2,"0"))}function fr(r,e){return Wt(r,e).reverse()}function hg(r){return ur(lr(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=ur(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(zt(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 It(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),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}function dg(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 pg(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Ja=r=>typeof r=="bigint"&&ec<=r;function Rn(r,e,t){return Ja(r)&&Ja(e)&&Ja(t)&&e<=r&&r<t}function $e(r,e,t,n){if(!Rn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function rc(r){let e;for(e=0;r>ec;r>>=jo,e+=1);return e}function mg(r,e){return r>>BigInt(e)&jo}function gg(r,e,t){return r|(t?jo:ec)<<BigInt(e)}var Dn=r=>(ug<<BigInt(r-1))-jo,Qa=r=>new Uint8Array(r),ff=r=>Uint8Array.from(r);function nc(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=Qa(r),o=Qa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Qa())=>{o=a(ff([0]),l),n=a(),l.length!==0&&(o=a(ff([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<e;){n=a();let h=n.slice();d.push(h),l+=n.length}return It(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var yg={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"||zt(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 ft(r,e,t={}){let n=(o,s,i)=>{let a=yg[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 wg=()=>{throw new Error("not implemented")};function hr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ye=BigInt(0),ne=BigInt(1),dr=BigInt(2),bg=BigInt(3),oc=BigInt(4),hf=BigInt(5),df=BigInt(8),xg=BigInt(9),vg=BigInt(16);function J(r,e){let t=r%e;return t>=ye?t:e+t}function Eg(r,e,t){if(t<=ye||e<ye)throw new Error("Expected power/modulo > 0");if(t===ne)return ye;let n=ne;for(;e>ye;)e&ne&&(n=n*r%t),r=r*r%t,e>>=ne;return n}function oe(r,e,t){let n=r;for(;e-- >ye;)n*=n,n%=t;return n}function Xo(r,e){if(r===ye||e<=ye)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=J(r,e),n=e,o=ye,s=ne,i=ne,a=ye;for(;t!==ye;){let u=n/t,f=n%t,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==ne)throw new Error("invert: does not exist");return J(o,e)}function Ag(r){let e=(r-ne)/dr,t,n,o;for(t=r-ne,n=0;t%dr===ye;t/=dr,n++);for(o=dr;o<r&&Eg(o,e,r)!==r-ne;o++);if(n===1){let i=(r+ne)/oc;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+ne)/dr;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),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,ne<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function Sg(r){if(r%oc===bg){let e=(r+ne)/oc;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%df===hf){let e=(r-hf)/df;return function(n,o){let s=n.mul(o,dr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,dr),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%vg,Ag(r)}var pf=(r,e)=>(J(r,e)&ne)===ne,_g=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=_g.reduce((n,o)=>(n[o]="function",n),e);return ft(r,t)}function Bg(r,e,t){if(t<ye)throw new Error("Expected power > 0");if(t===ye)return r.ONE;if(t===ne)return e;let n=r.ONE,o=e;for(;t>ye;)t&ne&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ne;return n}function Ig(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 ic(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function jt(r,e,t=!1,n={}){if(r<=ye)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=ic(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Sg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Dn(o),ZERO:ye,ONE:ne,create:c=>J(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&ne)===ne,neg:c=>J(-c,r),eql:(c,u)=>c===u,sqr:c=>J(c*c,r),add:(c,u)=>J(c+u,r),sub:(c,u)=>J(c-u,r),mul:(c,u)=>J(c*u,r),pow:(c,u)=>Bg(a,c,u),div:(c,u)=>J(c*Xo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Xo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Ig(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?fr(c,s):Wt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Gt(c):Bt(c)}});return Object.freeze(a)}function mf(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 ac(r){let e=mf(r);return e+Math.ceil(e/2)}function gf(r,e,t=!1){let n=r.length,o=mf(e),s=ac(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Gt(r),a=J(i,e-ne)+ne;return t?fr(a,o):Wt(a,o)}var Cg=BigInt(0),cc=BigInt(1),lc=new WeakMap,yf=new WeakMap;function Yo(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>Cg;)i&cc&&(a=a.add(c)),c=c.double(),i>>=cc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=cc);let b=g,w=g+Math.abs(y)-1,x=m%2!==0,A=y<0;y===0?l=l.add(t(x,i[b])):f=f.add(t(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=yf.get(s)||1,u=lc.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&lc.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),yf.set(s,i),lc.delete(s)}}}function Jo(r,e,t,n){if(!Array.isArray(t)||!Array.isArray(n)||n.length!==t.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!e.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),t.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=rc(BigInt(t.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((e.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(t[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function Mn(r){return sc(r.Fp),ft(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ic(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var st=BigInt(0),Ke=BigInt(1),Qo=BigInt(2),Tg=BigInt(8),Lg={zip215:!0};function Ng(r){let e=Mn(r);return ft(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function wf(r){let e=Ng(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Qo<<BigInt(a*8)-Ke,f=t.create,l=jt(e.n,e.nBitLength),d=e.uvRatio||((S,E)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(E))}}catch{return{isValid:!1,value:st}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,I)=>{if(ot("phflag",I),E.length||I)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){$e("coordinate "+S,E,st,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=hr((S,E)=>{let{ex:I,ey:N,ez:M}=S,U=S.is0();E==null&&(E=U?Tg:t.inv(M));let $=f(I*E),z=f(N*E),K=f(M*E);if(U)return{x:st,y:Ke};if(K!==Ke)throw new Error("invZ was invalid");return{x:$,y:z}}),b=hr(S=>{let{a:E,d:I}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:N,ey:M,ez:U,et:$}=S,z=f(N*N),K=f(M*M),Y=f(U*U),Q=f(Y*Y),xe=f(z*E),ve=f(Y*f(xe+K)),Ae=f(Q+f(I*f(z*K)));if(ve!==Ae)throw new Error("bad point: equation left != right (1)");let Pe=f(N*M),me=f(U*$);if(Pe!==me)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,I,N,M){this.ex=E,this.ey=I,this.ez=N,this.et=M,m("x",E),m("y",I),m("z",N),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");let{x:I,y:N}=E||{};return m("x",I),m("y",N),new w(I,N,Ke,f(I*N))}static normalizeZ(E){let I=t.invertBatch(E.map(N=>N.ez));return E.map((N,M)=>N.toAffine(I[M])).map(w.fromAffine)}static msm(E,I){return Jo(w,l,E,I)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:I,ey:N,ez:M}=this,{ex:U,ey:$,ez:z}=E,K=f(I*z),Y=f(U*M),Q=f(N*z),xe=f($*M);return K===Y&&Q===xe}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:I,ey:N,ez:M}=this,U=f(I*I),$=f(N*N),z=f(Qo*f(M*M)),K=f(E*U),Y=I+N,Q=f(f(Y*Y)-U-$),xe=K+$,ve=xe-z,Ae=K-$,Pe=f(Q*ve),me=f(xe*Ae),He=f(Q*Ae),wt=f(ve*xe);return new w(Pe,me,wt,He)}add(E){g(E);let{a:I,d:N}=e,{ex:M,ey:U,ez:$,et:z}=this,{ex:K,ey:Y,ez:Q,et:xe}=E;if(I===BigInt(-1)){let Cu=f((U-M)*(Y+K)),Tu=f((U+M)*(Y-K)),Pa=f(Tu-Cu);if(Pa===st)return this.double();let Lu=f($*Qo*xe),Nu=f(z*Qo*Q),Pu=Nu+Lu,Ru=Tu+Cu,Du=Nu-Lu,$p=f(Pu*Pa),Kp=f(Ru*Du),qp=f(Pu*Du),zp=f(Pa*Ru);return new w($p,Kp,zp,qp)}let ve=f(M*K),Ae=f(U*Y),Pe=f(z*N*xe),me=f($*Q),He=f((M+U)*(K+Y)-ve-Ae),wt=me-Pe,An=me+Pe,Sn=f(Ae-I*ve),Op=f(He*wt),Fp=f(An*Sn),Vp=f(He*Sn),Hp=f(wt*An);return new w(Op,Fp,Hp,Vp)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){let I=E;$e("scalar",I,Ke,n);let{p:N,f:M}=this.wNAF(I);return w.normalizeZ([N,M])[0]}multiplyUnsafe(E){let I=E;return $e("scalar",I,st,n),I===st?A:this.equals(A)||I===Ke?this:this.equals(x)?this.wNAF(I).p:_.unsafeLadder(this,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return y(this,E)}clearCofactor(){let{h:E}=e;return E===Ke?this:this.multiplyUnsafe(E)}static fromHex(E,I=!1){let{d:N,a:M}=e,U=t.BYTES;E=le("pointHex",E,U),ot("zip215",I);let $=E.slice(),z=E[U-1];$[U-1]=z&-129;let K=Gt($),Y=I?u:t.ORDER;$e("pointHex.y",K,st,Y);let Q=f(K*K),xe=f(Q-Ke),ve=f(N*Q-M),{isValid:Ae,value:Pe}=d(xe,ve);if(!Ae)throw new Error("Point.fromHex: invalid y coordinate");let me=(Pe&Ke)===Ke,He=(z&128)!==0;if(!I&&Pe===st&&He)throw new Error("Point.fromHex: x=0 and x_0=1");return He!==me&&(Pe=f(-Pe)),w.fromAffine({x:Pe,y:K})}static fromPrivateKey(E){return T(E).point}toRawBytes(){let{x:E,y:I}=this.toAffine(),N=fr(I,t.BYTES);return N[N.length-1]|=E&Ke?128:0,N}toHex(){return _t(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Ke,f(e.Gx*e.Gy)),w.ZERO=new w(st,Ke,Ke,st);let{BASE:x,ZERO:A}=w,_=Yo(w,a*8);function v(S){return J(S,n)}function B(S){return v(Gt(S))}function T(S){let E=a;S=le("private key",S,E);let I=le("hashed private key",s(S),2*E),N=h(I.slice(0,E)),M=I.slice(E,2*E),U=B(N),$=x.multiply(U),z=$.toRawBytes();return{head:N,prefix:M,scalar:U,point:$,pointBytes:z}}function re(S){return T(S).pointBytes}function V(S=new Uint8Array,...E){let I=It(...E);return B(s(p(I,le("context",S),!!o)))}function F(S,E,I={}){S=le("message",S),o&&(S=o(S));let{prefix:N,scalar:M,pointBytes:U}=T(E),$=V(I.context,N,S),z=x.multiply($).toRawBytes(),K=V(I.context,z,U,S),Y=v($+K*M);$e("signature.s",Y,st,n);let Q=It(z,fr(Y,t.BYTES));return le("result",Q,a*2)}let R=Lg;function k(S,E,I,N=R){let{context:M,zip215:U}=N,$=t.BYTES;S=le("signature",S,2*$),E=le("message",E),U!==void 0&&ot("zip215",U),o&&(E=o(E));let z=Gt(S.slice($,2*$)),K,Y,Q;try{K=w.fromHex(I,U),Y=w.fromHex(S.slice(0,$),U),Q=x.multiplyUnsafe(z)}catch{return!1}if(!U&&K.isSmallOrder())return!1;let xe=V(M,Y.toRawBytes(),K.toRawBytes(),E);return Y.add(K.multiplyUnsafe(xe)).subtract(Q).clearCofactor().equals(w.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:re,sign:F,verify:k,ExtendedPoint:w,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,E=w.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var uc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),bf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Wx=BigInt(0),Pg=BigInt(1),xf=BigInt(2),jx=BigInt(3),Rg=BigInt(5),Dg=BigInt(8);function Mg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=uc,a=r*r%s*r%s,c=oe(a,xf,s)*a%s,u=oe(c,Pg,s)*r%s,f=oe(u,Rg,s)*u%s,l=oe(f,e,s)*f%s,d=oe(l,t,s)*l%s,h=oe(d,n,s)*d%s,p=oe(h,o,s)*h%s,m=oe(p,o,s)*h%s,g=oe(m,e,s)*f%s;return{pow_p_5_8:oe(g,xf,s)*r%s,b2:a}}function Ug(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Og(r,e){let t=uc,n=J(e*e*e,t),o=J(n*n*e,t),s=Mg(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,u=J(i*bf,t),f=a===r,l=a===J(-r,t),d=a===J(-r*bf,t);return f&&(i=c),(l||d)&&(i=u),pf(i,t)&&(i=J(-i,t)),{isValid:f||l,value:i}}var Fg=jt(uc,void 0,!0),Vg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Fg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Dg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:lf,randomBytes:qr,adjustScalarBytes:Ug,uvRatio:Og},Un=wf(Vg);var es=32,ts=64,fc=32;function vf(){let r=Un.utils.randomPrivateKey(),e=Un.getPublicKey(r);return{privateKey:Hg(r,e),publicKey:e}}function Ef(r,e){let t=r.subarray(0,fc);return Un.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Af(r,e,t){return Un.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Hg(r,e){let t=new Uint8Array(ts);for(let n=0;n<fc;n++)t[n]=r[n],t[fc+n]=e[n];return t}var On=class{type="Ed25519";raw;constructor(e){this.raw=ns(e,es)}toMultihash(){return At.digest(ht(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return Af(this.raw,t,e)}},rs=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ns(e,ts),this.publicKey=new On(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Ef(this.raw,e)}};function hc(r){return r=ns(r,es),new On(r)}async function _f(){let{privateKey:r,publicKey:e}=vf();return new rs(r,e)}function ns(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new D(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function ue(r=0){return new Uint8Array(r)}function Ie(r=0){return new Uint8Array(r)}var $g=Math.pow(2,7),Kg=Math.pow(2,14),qg=Math.pow(2,21),dc=Math.pow(2,28),pc=Math.pow(2,35),mc=Math.pow(2,42),gc=Math.pow(2,49),j=128,ke=127;function pe(r){if(r<$g)return 1;if(r<Kg)return 2;if(r<qg)return 3;if(r<dc)return 4;if(r<pc)return 5;if(r<mc)return 6;if(r<gc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function yc(r,e,t=0){switch(pe(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 zg(r,e,t=0){switch(pe(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 wc(r,e){let t=r[e],n=0;if(n+=t&ke,t<j||(t=r[e+1],n+=(t&ke)<<7,t<j)||(t=r[e+2],n+=(t&ke)<<14,t<j)||(t=r[e+3],n+=(t&ke)<<21,t<j)||(t=r[e+4],n+=(t&ke)*dc,t<j)||(t=r[e+5],n+=(t&ke)*pc,t<j)||(t=r[e+6],n+=(t&ke)*mc,t<j)||(t=r[e+7],n+=(t&ke)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function Gg(r,e){let t=r.get(e),n=0;if(n+=t&ke,t<j||(t=r.get(e+1),n+=(t&ke)<<7,t<j)||(t=r.get(e+2),n+=(t&ke)<<14,t<j)||(t=r.get(e+3),n+=(t&ke)<<21,t<j)||(t=r.get(e+4),n+=(t&ke)*dc,t<j)||(t=r.get(e+5),n+=(t&ke)*pc,t<j)||(t=r.get(e+6),n+=(t&ke)*mc,t<j)||(t=r.get(e+7),n+=(t&ke)*gc,t<j))return n;throw new RangeError("Could not decode varint")}function Ce(r,e,t=0){return e==null&&(e=Ie(pe(r))),e instanceof Uint8Array?yc(r,e,t):zg(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?wc(r,e):Gg(r,e)}var bc=new Float32Array([-0]),Zt=new Uint8Array(bc.buffer);function Bf(r,e,t){bc[0]=r,e[t]=Zt[0],e[t+1]=Zt[1],e[t+2]=Zt[2],e[t+3]=Zt[3]}function If(r,e){return Zt[0]=r[e],Zt[1]=r[e+1],Zt[2]=r[e+2],Zt[3]=r[e+3],bc[0]}var xc=new Float64Array([-0]),Te=new Uint8Array(xc.buffer);function kf(r,e,t){xc[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function Cf(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],xc[0]}var Wg=BigInt(Number.MAX_SAFE_INTEGER),jg=BigInt(Number.MIN_SAFE_INTEGER),je=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 mr;if(e<Wg&&e>jg)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>Tf&&(o=0n,++n>Tf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return mr;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):mr}},mr=new je(0,0);mr.toBigInt=function(){return 0n};mr.zzEncode=mr.zzDecode=function(){return this};mr.length=function(){return 1};var Tf=4294967296n;function Lf(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 Nf(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 vc(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 os(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ec=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 os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=If(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Cf(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 Nf(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 je(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=os(this.buf,this.pos+=4),t=os(this.buf,this.pos+=4);return new je(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=wc(this.buf,this.pos);return this.pos+=pe(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ac(r){return new Ec(r instanceof Uint8Array?r:r.subarray())}function De(r,e,t){let n=Ac(r);return e.decode(n,void 0,t)}var Sc={};Re(Sc,{base10:()=>Zg});var Zg=$t({prefix:"9",name:"base10",alphabet:"0123456789"});var _c={};Re(_c,{base16:()=>Xg,base16upper:()=>Yg});var Xg=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yg=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Bc={};Re(Bc,{base2:()=>Jg});var Jg=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ic={};Re(Ic,{base256emoji:()=>n0});var Rf=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}"),Qg=Rf.reduce((r,e,t)=>(r[t]=e,r),[]),e0=Rf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function t0(r){return r.reduce((e,t)=>(e+=Qg[t],e),"")}function r0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=e0[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var n0=Ur({prefix:"\u{1F680}",name:"base256emoji",encode:t0,decode:r0});var Tc={};Re(Tc,{base64:()=>kc,base64pad:()=>o0,base64url:()=>Cc,base64urlpad:()=>s0});var kc=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),o0=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Cc=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),s0=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Lc={};Re(Lc,{base8:()=>i0});var i0=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Nc={};Re(Nc,{identity:()=>a0});var a0=Ur({prefix:"\0",name:"identity",encode:r=>$u(r),decode:r=>Hu(r)});var I1=new TextEncoder,k1=new TextDecoder;var Dc={};Re(Dc,{sha256:()=>Wr,sha512:()=>u0});function Rc({name:r,code:e,encode:t}){return new Pc(r,e,t)}var Pc=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?tt(this.code,t):t.then(n=>tt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Mf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Wr=Rc({name:"sha2-256",code:18,encode:Mf("SHA-256")}),u0=Rc({name:"sha2-512",code:19,encode:Mf("SHA-512")});var Fn={...Nc,...Bc,...Lc,...Sc,..._c,...qa,...za,...Ka,...Tc,...Ic},V1={...Dc,...ja};function Of(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Uf=Of("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Mc=Of("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=Ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),f0={utf8:Uf,"utf-8":Uf,hex:Fn.base16,latin1:Mc,ascii:Mc,binary:Mc,...Fn},ss=f0;function P(r,e="utf8"){let t=ss[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Uc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ie(i);o+i>e&&(n=Ie(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var gr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Oc(){}var Vc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},h0=Uc();function d0(r){return globalThis.Buffer!=null?Ie(r):h0(r)}var Hn=class{len;head;tail;states;constructor(){this.len=0,this.head=new gr(Oc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new gr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Hc((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(is,10,je.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=je.fromBigInt(e);return this._push(is,t.length(),t)}uint64Number(e){return this._push(yc,pe(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=je.fromBigInt(e).zzEncode();return this._push(is,t.length(),t)}sint64Number(e){let t=je.fromNumber(e).zzEncode();return this._push(is,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Fc,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=je.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=je.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,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(Bf,4,e)}double(e){return this._push(kf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Fc,1,0):this.uint32(t)._push(m0,t,e)}string(e){let t=Lf(e);return t!==0?this.uint32(t)._push(vc,t,e):this._push(Fc,1,0)}fork(){return this.states=new Vc(this),this.head=this.tail=new gr(Oc,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(Oc,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=d0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Fc(r,e,t){e[t]=r&255}function p0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Hc=class extends gr{next;constructor(e,t){super(p0,e,t),this.next=void 0}};function is(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 Vn(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 m0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Hn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(g0,e,r),this},Hn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(y0,e,r),this});function g0(r,e,t){e.set(r,t)}function y0(r,e,t){r.length<40?vc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function $c(){return new Hn}function Me(r,e){let t=$c();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var jr;(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"})(jr||(jr={}));function as(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Kc(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 as("enum",jr.VARINT,t,n)}function Ue(r,e){return as("message",jr.LENGTH_DELIMITED,r,e)}var yr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},$n=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var we;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(we||(we={}));var qc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(qc||(qc={}));(function(r){r.codec=()=>Kc(qc)})(we||(we={}));var dt;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(dt||(dt={}));var zc;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(zc||(zc={}));var Qn={};Re(Qn,{MAX_RSA_KEY_SIZE:()=>Js,generateRSAKeyPair:()=>rl,jwkToJWKKeyPair:()=>Dh,jwkToPkcs1:()=>P0,jwkToPkix:()=>el,jwkToRSAPrivateKey:()=>Rh,pkcs1ToJwk:()=>Lh,pkcs1ToRSAPrivateKey:()=>Ph,pkixToJwk:()=>Nh,pkixToRSAPublicKey:()=>tl});var w0=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]),Xt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yt=new Uint32Array(64),Gc=class extends zr{constructor(){super(64,32,8,!1),this.A=Xt[0]|0,this.B=Xt[1]|0,this.C=Xt[2]|0,this.D=Xt[3]|0,this.E=Xt[4]|0,this.F=Xt[5]|0,this.G=Xt[6]|0,this.H=Xt[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)Yt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Yt[l-15],h=Yt[l-2],p=nt(d,7)^nt(d,18)^d>>>3,m=nt(h,17)^nt(h,19)^h>>>10;Yt[l]=m+Yt[l-7]+p+Yt[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 d=nt(a,6)^nt(a,11)^nt(a,25),h=f+d+sf(a,c,u)+w0[l]+Yt[l]|0,m=(nt(n,2)^nt(n,13)^nt(n,22))+af(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|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(){Yt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Zr=Go(()=>new Gc);var q=ar(Vf());function wr(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 Jt(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 us(...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 jc(){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=wr(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,wr(s,8)-n}function Hf(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=Jt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jt(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 $f(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 qe(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 vv=Math.log(2);function fs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Zc(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 Nt(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 qn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Zc(this.items)}},Kn=[new Uint8Array([1])],Kf="0123456789";var en="",ct=new ArrayBuffer(0),Xc=new Uint8Array(0),zn="EndOfContent",zf="OCTET STRING",Gf="BIT STRING";function Pt(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?q.BufferSourceConverter.toUint8Array(s.valueHex):Xc}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(!Nt(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",ct)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Ct=class{constructor({blockLength:e=0,error:t=en,warnings:n=[],valueBeforeDecode:o=Xc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.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:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Ct.NAME="baseBlock";var Le=class extends Ct{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'")}};Le.NAME="valueBlock";var hs=class extends Pt(Ct){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?q.BufferSourceConverter.toUint8Array(e.valueHex):Xc,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",ct}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=Jt(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=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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 d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[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 d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=wr(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}}};hs.NAME="identificationBlock";var ds=class extends Ct{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=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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=wr(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=Jt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ct;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}}};ds.NAME="lengthBlock";var C={},Se=class extends Ct{constructor({name:e=en,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new hs(o),this.lenBlock=new ds(o),this.valueBlock=s?new s(o):new Le(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 qn;t||Wf(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?ct: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():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.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 $f(t,n)}};Se.NAME="BaseBlock";function Wf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Wf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ps=class extends Se{constructor({value:e=en,...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}'`}};ps.NAME="BaseStringBlock";var ms=class extends Pt(Le){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};ms.NAME="PrimitiveValueBlock";var jf,gs=class extends Se{constructor(e={}){super(e,ms),this.idBlock.isConstructed=!1}};jf=gs;C.Primitive=jf;gs.NAME="PRIMITIVE";function I0(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 Xs(r,e=0,t=r.length){let n=e,o=new Se({},Le),s=new Ct;if(!Nt(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=Se;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=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.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?C.Constructed:C.Primitive}return o=I0(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 Yc(r){if(!r.byteLength){let e=new Se({},Le);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Xs(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function k0(r,e){return r?1:e}var pt=class extends Le{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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(;k0(this.isIndefiniteForm,n)>0;){let i=Xs(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===zn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===zn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new qn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ct:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};pt.NAME="ConstructedValueBlock";var Zf,Qt=class extends Se{constructor(e={}){super(e,pt),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
3
  `).map(o=>` ${o}`).join(`
4
- `));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
5
- ${t.join(`
6
- `)}`:`${e} :`}};Gf=Je;C.Constructed=Gf;Je.NAME="CONSTRUCTED";var gs=class extends Lt{fromBER(t,e,n){return e}toBER(t){return ae}};gs.override="EndOfContentValueBlock";var Wf,ys=class extends At{constructor(t={}){super(t,gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Wf=ys;C.EndOfContent=Wf;ys.NAME=Kn;var jf,Xr=class extends At{constructor(t={}){super(t,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,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,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};jf=Xr;C.Null=jf;Xr.NAME="NULL";var ws=class extends Re(Lt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);return Pe(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,qc.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ws.NAME="BooleanValueBlock";var Zf,bs=class extends At{constructor(t={}){super(t,ws),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Zf=bs;C.Boolean=Zf;bs.NAME="BOOLEAN";var xs=class extends Re(de){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=de.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Kn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==$f)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?de.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};xs.NAME="OctetStringValueBlock";var Xf,vs=class r extends At{constructor({idBlock:t={},lenBlock:e={},...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,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},xs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,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),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=Zs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Je.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return q.BufferSourceConverter.concat(t)}};Xf=vs;C.OctetString=Xf;vs.NAME=$f;var Es=class extends Re(de){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=de.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Kn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Kf)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=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,s,e,n))return-1;let i=s.subarray(e,e+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=Zs(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,e+n}toBER(t,e){if(this.isConstructed)return de.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ae;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}}};Es.NAME="BitStringValueBlock";var Yf,Yr=class extends At{constructor({idBlock:t={},lenBlock:e={},...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,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Es),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Je.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Yf=Yr;C.BitString=Yf;Yr.NAME=Kf;var Jf;function k0(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),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 d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+e[0];break;default:u=s[i-l]+e[0]}switch(e[0]=u/10,!0){case l>=s.length:s=ls(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return e[0]>0&&(s=ls(e,s)),s}function Hf(r){if(r>=Hn.length)for(let t=Hn.length;t<=r;t++){let e=new Uint8Array([0]),n=Hn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=ls(e,n)),Hn.push(n)}return Hn[r]}function C0(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),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]-e,!0){case u<0:e=1,s[i-f]=u+10;break;default:e=0,s[i-f]=u}if(e>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-e,u<0)e=1,s[i-f]=u+10;else{e=0,s[i-f]=u;break}return s.slice()}var qn=class extends Re(Lt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=qc.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Of(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,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(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=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 t:e=C0(Hf(n),e),i="-";break;default:e=k0(e,Hf(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Vf.charAt(e[c]));return a===!1&&(i+=Vf.charAt(0)),i}};Jf=qn;qn.NAME="IntegerValueBlock";Object.defineProperty(Jf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Qf,St=class r extends At{constructor(t={}){super(t,qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return us(),BigInt(this.valueBlock.toString())}static fromBigInt(t){us();let e=BigInt(t),n=new $n,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+e,f=q.BufferSourceConverter.toUint8Array(q.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 t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}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()}`}};Qf=St;C.Integer=Qf;St.NAME="INTEGER";var th,As=class extends St{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};th=As;C.Enumerated=th;As.NAME="ENUMERATED";var zn=class extends Re(Lt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+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=yr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){us();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)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 e=Ye(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ae;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};zn.NAME="sidBlock";var Ss=class extends Lt{constructor({value:t=Qr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new zn;if(o=s.fromBER(t,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(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ae;e.push(o)}return zc(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=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 zn;if(o>Number.MAX_SAFE_INTEGER){us();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 t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ss.NAME="ObjectIdentifierValueBlock";var eh,Jr=class extends At{constructor(t={}){super(t,Ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};eh=Jr;C.ObjectIdentifier=eh;Jr.NAME="OBJECT IDENTIFIER";var Gn=class extends Re(Te){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+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=yr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)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 e=Ye(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ae;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=q.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Gn.NAME="relativeSidBlock";var _s=class extends Lt{constructor({value:t=Qr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Gn;if(o=s.fromBER(t,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(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ae;n.push(s)}return zc(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new Gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};_s.NAME="RelativeObjectIdentifierValueBlock";var rh,Bs=class extends At{constructor(t={}){super(t,_s),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};rh=Bs;C.RelativeObjectIdentifier=rh;Bs.NAME="RelativeObjectIdentifier";var nh,Le=class extends Je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};nh=Le;C.Sequence=nh;Le.NAME="SEQUENCE";var oh,Is=class extends Je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};oh=Is;C.Set=oh;Is.NAME="SET";var ks=class extends Re(Lt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Qr}toJSON(){return{...super.toJSON(),value:this.value}}};ks.NAME="StringValueBlock";var Cs=class extends ks{};Cs.NAME="SimpleStringValueBlock";var Ot=class extends ds{constructor({...t}={}){super(t,Cs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ot.NAME="SIMPLE STRING";var Ts=class extends Ot{fromBuffer(t){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=q.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ts.NAME="Utf8StringValueBlock";var sh,Ne=class extends Ts{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};sh=Ne;C.Utf8String=sh;Ne.NAME="UTF8String";var Ls=class extends Ot{fromBuffer(t){this.valueBlock.value=q.Convert.ToUtf16String(t),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(t))}};Ls.NAME="BmpStringValueBlock";var ih,Ns=class extends Ls{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};ih=Ns;C.BmpString=ih;Ns.NAME="BMPString";var Ps=class extends Ot{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);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(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ye(t.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=t}};Ps.NAME="UniversalStringValueBlock";var ah,Rs=class extends Ps{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ah=Rs;C.UniversalString=ah;Rs.NAME="UniversalString";var ch,Ds=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ch=Ds;C.NumericString=ch;Ds.NAME="NumericString";var lh,Ms=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};lh=Ms;C.PrintableString=lh;Ms.NAME="PrintableString";var uh,Us=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};uh=Us;C.TeletexString=uh;Us.NAME="TeletexString";var fh,Os=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};fh=Os;C.VideotexString=fh;Os.NAME="VideotexString";var hh,Fs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};hh=Fs;C.IA5String=hh;Fs.NAME="IA5String";var dh,Vs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};dh=Vs;C.GraphicString=dh;Vs.NAME="GraphicString";var ph,Wn=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ph=Wn;C.VisibleString=ph;Wn.NAME="VisibleString";var mh,Hs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};mh=Hs;C.GeneralString=mh;Hs.NAME="GeneralString";var gh,$s=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};gh=$s;C.CharacterString=gh;$s.NAME="CharacterString";var yh,jn=class extends Wn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);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(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=qt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=qt(this.month,2),e[2]=qt(this.day,2),e[3]=qt(this.hour,2),e[4]=qt(this.minute,2),e[5]=qt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}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}}};yh=jn;C.UTCTime=yh;jn.NAME="UTCTime";var wh,Ks=class extends jn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let l=new Number(t[t.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){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,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}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(e===!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(t="iso"){if(t==="iso"){let e=[];return e.push(qt(this.year,4)),e.push(qt(this.month,2)),e.push(qt(this.day,2)),e.push(qt(this.hour,2)),e.push(qt(this.minute,2)),e.push(qt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(qt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};wh=Ks;C.GeneralizedTime=wh;Ks.NAME="GeneralizedTime";var bh,qs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};bh=qs;C.DATE=bh;qs.NAME="DATE";var xh,zs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};xh=zs;C.TimeOfDay=xh;zs.NAME="TimeOfDay";var vh,Gs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vh=Gs;C.DateTime=vh;Gs.NAME="DateTime";var Eh,Ws=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Eh=Ws;C.Duration=Eh;Ws.NAME="Duration";var Ah,js=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ah=js;C.TIME=Ah;js.NAME="TIME";function H(r,t="utf8"){let e=os[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function tn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Kr(r)}var Zn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Xn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Xs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Sh={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Xs("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");return t}};var Qe=Sh;async function _h(r){let t=await Qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await L0(t);return{privateKey:e[0],publicKey:e[1]}}async function Bh(r,t){let e=await Qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ih(r,t,e){let n=await Qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function L0(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([Qe.get().subtle.exportKey("jwk",r.privateKey),Qe.get().subtle.exportKey("jwk",r.publicKey)])}function jc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var en=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pt.createV1(114,this._multihash)}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return Ih(this._key,e,t)}},Jn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return Bh(this._key,t)}};var Ys=8192,Zc=18;function kh(r){let{result:t}=Wc(r),e=t.valueBlock.value;return{n:H(pe(e[1].toBigInt()),"base64url"),e:H(pe(e[2].toBigInt()),"base64url"),d:H(pe(e[3].toBigInt()),"base64url"),p:H(pe(e[4].toBigInt()),"base64url"),q:H(pe(e[5].toBigInt()),"base64url"),dp:H(pe(e[6].toBigInt()),"base64url"),dq:H(pe(e[7].toBigInt()),"base64url"),qi:H(pe(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function N0(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 D("JWK was missing components");let e=new Le({value:[new St({value:0}),St.fromBigInt(me(P(r.n,"base64url"))),St.fromBigInt(me(P(r.e,"base64url"))),St.fromBigInt(me(P(r.d,"base64url"))),St.fromBigInt(me(P(r.p,"base64url"))),St.fromBigInt(me(P(r.q,"base64url"))),St.fromBigInt(me(P(r.dp,"base64url"))),St.fromBigInt(me(P(r.dq,"base64url"))),St.fromBigInt(me(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Ch(r){let{result:t}=Wc(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(pe(e[0].toBigInt()),"base64url"),e:H(pe(e[1].toBigInt()),"base64url")}}function Xc(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let e=new Le({value:[new Le({value:[new Jr({value:"1.2.840.113549.1.1.1"}),new Xr]}),new Yr({valueHex:new Le({value:[St.fromBigInt(me(P(r.n,"base64url"))),St.fromBigInt(me(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function pe(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,s=0;for(;o<e;)n[o]=parseInt(t.slice(s,s+2),16),o+=1,s+=2;return n}function me(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Th(r){let t=kh(r);return Lh(t)}function Yc(r){let t=Ch(r);if(jc(t)>Ys)throw new Nr("Key size is too large");let e=jr(he.encode({Type:gt.RSA,Data:r})),n=te(Zc,e);return new en(t,n)}function Lh(r){if(jc(r)>Ys)throw new D("Key size is too large");let t=Nh(r),e=jr(he.encode({Type:gt.RSA,Data:Xc(t.publicKey)})),n=te(Zc,e);return new Jn(t.privateKey,new en(t.publicKey,n))}async function Jc(r){if(r>Ys)throw new D("Key size is too large");let t=await _h(r),e=jr(he.encode({Type:gt.RSA,Data:Xc(t.publicKey)})),n=te(Zc,e);return new Jn(t.privateKey,new en(t.publicKey,n))}function Nh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Js=class extends $r{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qu(t);let n=Ln(e);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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Hr(this),this.iHash.update(t),this}digestInto(t){Hr(this),Vr(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:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Qc=(r,t,e)=>new Js(r,t).update(e).digest();Qc.create=(r,t)=>new Js(r,t);function Ph(r){r.lowS!==void 0&&ne("lowS",r.lowS),r.prehash!==void 0&&ne("prehash",r.prehash)}function P0(r){let t=Rn(r);ue(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:R0,hexToBytes:D0}=jo,De={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=De;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=cr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?cr(o.length/2|128):"";return`${cr(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=De,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=De;if(r<Me)throw new t("integer: negative integers are not allowed");let e=cr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=De;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return R0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=De,o=typeof r=="string"?D0(r):r;zr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=De,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Me=BigInt(0),vt=BigInt(1),e2=BigInt(2),Rh=BigInt(3),r2=BigInt(4);function M0(r){let t=P0(r),{Fp:e}=t,n=We(t.n,t.nBitLength),o=t.toBytes||((m,g,y)=>{let b=g.toAffine();return ke(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let g=m.subarray(1),y=e.fromBytes(g.subarray(0,e.BYTES)),b=e.fromBytes(g.subarray(e.BYTES,2*e.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=t,b=e.sqr(m),w=e.mul(b,m);return e.add(e.add(w,e.mul(m,g)),y)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Nn(m,vt,t.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=t;if(g&&typeof m!="bigint"){if(qe(m)&&(m=Be(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Ie(at("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=Y(x,w)),$t("private key",x,vt,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=fr((m,g)=>{let{px:y,py:b,pz:w}=m;if(e.eql(w,e.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?e.ONE:e.inv(w));let A=e.mul(y,g),_=e.mul(b,g),v=e.mul(w,g);if(x)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=fr(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!e.isValid(g)||!e.isValid(y))throw new Error("bad point: x or y not FE");let b=e.sqr(y),w=i(g);if(!e.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!e.isValid(g))throw new Error("x required");if(y==null||!e.isValid(y))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!e.isValid(y)||!e.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>e.eql(x,e.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=e.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(at("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Yo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(e.isOdd)return!e.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=e.eql(e.mul(y,_),e.mul(x,w)),B=e.eql(e.mul(b,_),e.mul(A,w));return v&&B}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:g,b:y}=t,b=e.mul(y,Rh),{px:w,py:x,pz:A}=this,_=e.ZERO,v=e.ZERO,B=e.ZERO,T=e.mul(w,w),et=e.mul(x,x),V=e.mul(A,A),F=e.mul(w,x);return F=e.add(F,F),B=e.mul(w,A),B=e.add(B,B),_=e.mul(g,B),v=e.mul(b,V),v=e.add(_,v),_=e.sub(et,v),v=e.add(et,v),v=e.mul(_,v),_=e.mul(F,_),B=e.mul(b,B),V=e.mul(g,V),F=e.sub(T,V),F=e.mul(g,F),F=e.add(F,B),B=e.add(T,T),T=e.add(B,T),T=e.add(T,V),T=e.mul(T,F),v=e.add(v,T),V=e.mul(x,A),V=e.add(V,V),T=e.mul(V,F),_=e.sub(_,T),B=e.mul(V,et),B=e.add(B,B),B=e.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=e.ZERO,B=e.ZERO,T=e.ZERO,et=t.a,V=e.mul(t.b,Rh),F=e.mul(y,x),R=e.mul(b,A),k=e.mul(w,_),L=e.add(y,b),S=e.add(x,A);L=e.mul(L,S),S=e.add(F,R),L=e.sub(L,S),S=e.add(y,w);let E=e.add(x,_);return S=e.mul(S,E),E=e.add(F,k),S=e.sub(S,E),E=e.add(b,w),v=e.add(A,_),E=e.mul(E,v),v=e.add(R,k),E=e.sub(E,v),T=e.mul(et,S),v=e.mul(V,k),T=e.add(v,T),v=e.sub(R,T),T=e.add(R,T),B=e.mul(v,T),R=e.add(F,F),R=e.add(R,F),k=e.mul(et,k),S=e.mul(V,S),R=e.add(R,k),k=e.sub(F,k),k=e.mul(et,k),S=e.add(S,k),F=e.mul(R,S),B=e.add(B,F),F=e.mul(E,S),v=e.mul(L,v),v=e.sub(v,F),F=e.mul(L,R),T=e.mul(E,T),T=e.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$t("scalar",g,Me,t.n);let y=d.ZERO;if(g===Me)return y;if(g===vt)return this;let{endo:b}=t;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Me||_>Me;)x&vt&&(v=v.add(T)),_&vt&&(B=B.add(T)),T=T.double(),x>>=vt,_>>=vt;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(e.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=t;$t("scalar",g,vt,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:et}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(e.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=et.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Me||v===vt||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=t;if(g===vt)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=t;return g===vt?this:y?y(d,this):this.multiplyUnsafe(t.h)}toRawBytes(g=!0){return ne("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return ne("isCompressed",g),Be(this.toRawBytes(g))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,p=Xo(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function U0(r){let t=Rn(r);return ue(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Dh(r){let t=U0(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(k){return Y(k,n)}function a(k){return Zo(k,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=M0({...t,toBytes(k,L,S){let E=L.toAffine(),I=e.toBytes(E.x),N=ke;return ne("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),I):N(Uint8Array.from([4]),I,e.toBytes(E.y))},fromBytes(k){let L=k.length,S=k[0],E=k.subarray(1);if(L===o&&(S===2||S===3)){let I=Ie(E);if(!Nn(I,vt,e.ORDER))throw new Error("Point is not on curve");let N=f(I),M;try{M=e.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&vt)===vt;return(S&1)===1!==U&&(M=e.neg(M)),{x:I,y:M}}else if(L===s&&S===4){let I=e.fromBytes(E.subarray(0,e.BYTES)),N=e.fromBytes(E.subarray(e.BYTES,2*e.BYTES));return{x:I,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=k=>Be(Ge(k,t.nByteLength));function h(k){let L=n>>vt;return k>L}function p(k){return h(k)?i(-k):k}let m=(k,L,S)=>Ie(k.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=t.nByteLength;return L=at("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=De.toSig(at("DER",L));return new g(S,E)}assertValidity(){$t("r",this.r,vt,n),$t("s",this.s,vt,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:I}=this,N=_(at("msgHash",L));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let M=I===2||I===3?S+t.n:S;if(M>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=I&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),X=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,X);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return lr(this.toDERHex())}toDERHex(){return De.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return lr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(k){try{return u(k),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let k=nc(t.n);return df(t.randomBytes(k),t.n)},precompute(k=8,L=c.BASE){return L._setWindowSize(k),L.multiply(BigInt(3)),L}};function b(k,L=!0){return c.fromPrivateKey(k).toRawBytes(L)}function w(k){let L=qe(k),S=typeof k=="string",E=(L||S)&&k.length;return L?E===o||E===s:S?E===2*o||E===2*s:k instanceof c}function x(k,L,S=!0){if(w(k))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(k)).toRawBytes(S)}let A=t.bits2int||function(k){let L=Ie(k),S=k.length*8-t.nBitLength;return S>0?L>>BigInt(S):L},_=t.bits2int_modN||function(k){return i(A(k))},v=Pn(t.nBitLength);function B(k){return $t(`num < 2^${t.nBitLength}`,k,Me,v),Ge(k,t.nByteLength)}function T(k,L,S=et){if(["recovered","canonical"].some(xt=>xt in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:I}=t,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),k=at("msgHash",k),Ph(S),M&&(k=at("prehashed msgHash",E(k)));let $=_(k),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let xt=U===!0?I(e.BYTES):U;K.push(at("extraEntropy",xt))}let X=ke(...K),Q=$;function bt(xt){let Et=A(xt);if(!l(Et))return;let Pt=a(Et),dt=c.BASE.multiply(Et).toAffine(),Ht=i(dt.x);if(Ht===Me)return;let we=i(Pt*i(Q+Ht*z));if(we===Me)return;let En=(dt.x===Ht?0:2)|Number(dt.y&vt),An=we;return N&&h(we)&&(An=p(we),En^=1),new g(Ht,An,En)}return{seed:X,k2sig:bt}}let et={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function F(k,L,S=et){let{seed:E,k2sig:I}=T(k,L,S),N=t;return Qa(N.hash.outputLen,N.nByteLength,N.hmac)(E,I)}c.BASE._setWindowSize(8);function R(k,L,S,E=V){let I=k;if(L=at("msgHash",L),S=at("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");Ph(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof I=="string"||qe(I))try{U=g.fromDER(I)}catch(dt){if(!(dt instanceof De.Err))throw dt;U=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:dt,s:Ht}=I;U=new g(dt,Ht)}else throw new Error("PARSE");$=c.fromHex(S)}catch(dt){if(dt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=t.hash(L));let{r:z,s:K}=U,X=_(L),Q=a(K),bt=i(X*Q),xt=i(z*Q),Et=c.BASE.multiplyAndAddUnsafe($,bt,xt)?.toAffine();return Et?i(Et.x)===z:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function O0(r){return{hash:r,hmac:(t,...e)=>Qc(r,t,za(...e)),randomBytes:Kr}}function Mh(r,t){let e=n=>Dh({...r,...O0(n)});return Object.freeze({...e(t),create:e})}var Fh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),F0=BigInt(1),tl=BigInt(2),Oh=(r,t)=>(r+t/tl)/t;function V0(r){let t=Fh,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=nt(f,e,t)*f%t,d=nt(l,e,t)*f%t,h=nt(d,tl,t)*u%t,p=nt(h,o,t)*h%t,m=nt(p,s,t)*p%t,g=nt(m,a,t)*m%t,y=nt(g,c,t)*g%t,b=nt(y,a,t)*m%t,w=nt(b,e,t)*f%t,x=nt(w,i,t)*p%t,A=nt(x,n,t)*u%t,_=nt(A,tl,t);if(!el.eql(el.sqr(_),r))throw new Error("Cannot find square root");return _}var el=We(Fh,void 0,void 0,{sqrt:V0}),Xt=Mh({a:BigInt(0),b:BigInt(7),Fp:el,n:Uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Uh,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-F0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Oh(s*r,t),c=Oh(-n*r,t),u=Y(r-a*e-c*o,t),f=Y(-a*n-c*s,t),l=u>i,d=f>i;if(l&&(u=t-u),d&&(f=t-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},jr),f2=BigInt(0);var h2=Xt.ProjectivePoint;function Ft(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=It(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function rl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Vh(r,t){let e=Gr.digest(t instanceof Uint8Array?t:t.subarray());if(rl(e))return e.then(({digest:n})=>Xt.sign(n,r).toDERRawBytes()).catch(n=>{throw new Zn(String(n))});try{return Xt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Zn(String(n))}}function Hh(r,t,e){let n=Gr.digest(e instanceof Uint8Array?e:e.subarray());if(rl(n))return n.then(({digest:o})=>Xt.verify(t,o,r)).catch(o=>{throw new Xn(String(o))});try{return Xt.verify(t,n.digest,r)}catch(o){throw new Xn(String(o))}}var Qn=class{type="secp256k1";raw;_key;constructor(t){this._key=qh(t),this.raw=$h(this._key)}toMultihash(){return Se.digest(fe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return Hh(this._key,e,t)}},Qs=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Kh(t),this.publicKey=new Qn(e??zh(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return Vh(this.raw,t)}};function nl(r){return new Qn(r)}async function Gh(){let r=H0();return new Qs(r)}function $h(r){return Xt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Kh(r){try{return Xt.getPublicKey(r,!0),r}catch(t){throw new Sn(String(t))}}function qh(r){try{return Xt.ProjectivePoint.fromHex(r),r}catch(t){throw new Nr(String(t))}}function zh(r){try{return Xt.getPublicKey(r,!0)}catch(t){throw new Sn(String(t))}}function H0(){return Xt.utils.randomPrivateKey()}async function Wh(r,t){if(r==="Ed25519")return Ef();if(r==="secp256k1")return Gh();if(r==="RSA")return Jc(t??2048);throw new Ve}function rn(r){let{Type:t,Data:e}=he.decode(r),n=e??new Uint8Array;switch(t){case gt.RSA:return Yc(n);case gt.Ed25519:return cc(n);case gt.secp256k1:return nl(n);default:throw new Ve}}function jh(r){let{Type:t,Data:e}=he.decode(r.digest),n=e??new Uint8Array;switch(t){case gt.Ed25519:return cc(n);case gt.secp256k1:return nl(n);default:throw new Ve}}function fe(r){return he.encode({Type:gt[r.type],Data:r.raw})}var Zh=Symbol.for("nodejs.util.inspect.custom"),$0=114,to=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Lo]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pt.createV1($0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return it(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return it(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Zh](){return`PeerId(${this.toString()})`}},eo=class extends to{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ro=class extends to{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},no=class extends to{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},K0=2336,oo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Se.digest(P(this.url))}[Zh](){return`PeerId(${this.url})`}[Lo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pt.createV1(K0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};var q0=114,Xh=2336;function ge(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=ee(W.decode(`z${r}`));else{if(t==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=ee(t.decode(r))}return nn(e)}function ol(r){if(r.type==="Ed25519")return new ro({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new eo({multihash:r.toCID().multihash,publicKey:r});throw new Ve}function Yh(r){return ol(r.publicKey)}function nn(r){if(G0(r))return new eo({multihash:r});if(z0(r))try{let t=jh(r);if(t.type==="Ed25519")return new ro({multihash:r,publicKey:t});if(t.type==="secp256k1")return new no({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new oo(new URL(e))}throw new Uo("Supplied PeerID Multihash is invalid")}function ti(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==q0&&r.code!==Xh)throw new Mo("Supplied PeerID CID is invalid");if(r.code===Xh){let t=H(r.multihash.digest);return new oo(new URL(t))}return nn(r.multihash)}function z0(r){return r.code===Se.code}function G0(r){return r.code===Gr.code}var ei=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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 e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,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 d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jh=45,W0=15,on=new ei;function sl(r){if(!(r.length>W0))return on.new(r).parseWith(()=>on.readIPv4Addr())}function il(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return on.new(r).parseWith(()=>on.readIPv6Addr())}function ri(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return on.new(r).parseWith(()=>on.readIPAddr())}function sn(r){return!!sl(r)}function an(r){return!!il(r)}function ni(r){return!!ri(r)}var vE=parseInt("0xFFFF",16),EE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ed=sn,J0=an,al=function(r){let t=0;if(r=r.toString().trim(),ed(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(J0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=ed(e[n]),i;s&&(i=al(e[n]),e[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},rd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var cn={},cl={},ty=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];ty.forEach(r=>{let t=ey(...r);cl[t.code]=t,cn[t.name]=t});function ey(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(cl[r]!=null)return cl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(cn[r]!=null)return cn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var nA=Z("ip4"),oA=Z("ip6"),sA=Z("ipcidr");function hl(r,t){switch(Z(r).code){case 4:case 41:return ny(t);case 42:return fl(t);case 6:case 273:case 33:case 132:return sd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return fl(t);case 421:return ay(t);case 444:return od(t);case 445:return od(t);case 466:return iy(t);case 481:return globalThis.encodeURIComponent(fl(t));default:return H(t,"base16")}}function dl(r,t){switch(Z(r).code){case 4:return nd(t);case 41:return nd(t);case 42:return ul(t);case 6:case 273:case 33:case 132:return pl(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ul(t);case 421:return oy(t);case 444:return cy(t);case 445:return ly(t);case 466:return sy(t);case 481:return ul(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}var ll=Object.values(Un).map(r=>r.decoder),ry=function(){let r=ll[0].or(ll[1]);return ll.slice(2).forEach(t=>r=r.or(t)),r}();function nd(r){if(!ni(r))throw new Error("invalid ip address");return al(r)}function ny(r){let t=rd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ni(t))throw new Error("invalid ip address");return t}function pl(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function sd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ul(r){let t=P(r),e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function fl(r){let t=se(r);if(r=r.slice(ht(t)),r.length!==t)throw new Error("inconsistent lengths");return H(r)}function oy(r){let t;r[0]==="Q"||r[0]==="1"?t=ee(W.decode(`z${r}`)).bytes:t=pt.parse(r).multihash.bytes;let e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function sy(r){let t=ry.decode(r),e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function iy(r){let t=se(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+H(e,"base64url")}function ay(r){let t=se(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return H(e,"base58btc")}function cy(r){let t=r.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 e=zt.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 o=pl(n);return Ft([e,o],e.length+o.length)}function ly(r){let t=r.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 e=zt.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 o=pl(n);return Ft([e,o],e.length+o.length)}function od(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=H(t,"base32"),o=sd(e);return`${n}:${o}`}function id(r){r=ml(r);let t=[],e=[],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=Z(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw cd("invalid address: "+r);if(a.path===!0){n=ml(o.slice(s).join("/")),t.push([a.code,dl(a.code,n)]),e.push([a.code,n]);break}let c=dl(a.code,o[s]);t.push([a.code,c]),e.push([a.code,hl(a.code,c)])}return{string:ad(e),bytes:yl(t),tuples:t,stringTuples:e,path:n}}function gl(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=se(r,o),i=ht(s),a=Z(s),c=uy(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw cd("Invalid address Uint8Array: "+H(r,"base16"));t.push([s,u]);let f=hl(s,u);if(e.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:ad(e),tuples:t,stringTuples:e,path:n}}function ad(r){let t=[];return r.map(e=>{let n=Z(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ml(t.join("/"))}function yl(r){return Ft(r.map(t=>{let e=Z(t[0]),n=Uint8Array.from(Ct(e.code));return t.length>1&&t[1]!=null&&(n=Ft([n,t[1]])),n}))}function uy(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=se(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ht(e)}}function ml(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function cd(r){return new Error("Error parsing address: "+r)}var fy=Symbol.for("nodejs.util.inspect.custom"),bl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),hy=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],wl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},oi=class r{bytes;#t;#e;#s;#a;[bl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=gl(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=id(t)}else if(tr(t))e=gl(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#s=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),hy.includes(h)&&(e=i.name,o=443,n=`${p??""}${s}`,t=h===f.code?6:4),(h===i.code||h===a.code)&&(e=Z(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(e=Z(h).name,n=`${p??""}${s}`,t=h===u.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},Z(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Z(t).name)}tuples(){return this.#e}stringTuples(){return this.#s}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(yl(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===cn.p2p.code&&t.push([n,o]),n===cn["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return it(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=ln.get(e.name);if(n==null)throw new wl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ot(s))}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 e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[fy](){return`Multiaddr(${this.#t})`}};var ln=new Map;function tr(r){return!!r?.[bl]}function ot(r){return new oi(r)}var dy=r=>r.toString().split("/").slice(1),so=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),G=r=>({match:t=>so(e=>e===r).match(t),pattern:r}),ai=()=>({match:r=>so(t=>typeof t=="string").match(r),pattern:"{string}"}),ci=()=>({match:r=>so(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),_t=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),si=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{_c.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),yt=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Yt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),J=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function ut(...r){function t(o){let s=dy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var vl=J(G("dns4"),ai()),El=J(G("dns6"),ai()),Al=J(G("dnsaddr"),ai()),ld=J(G("dns"),ai()),PA=ut(vl),RA=ut(El),DA=ut(Al),MA=ut(Yt(ld,Al,vl,El)),ud=J(G("ip4"),so(sn)),fd=J(G("ip6"),so(an)),hd=Yt(ud,fd),ye=Yt(hd,ld,vl,El,Al),UA=ut(ye),OA=ut(ud),FA=ut(fd),VA=ut(hd),Sl=J(ye,G("tcp"),ci()),io=J(ye,G("udp"),ci()),HA=ut(Sl),$A=ut(io),_l=J(io,G("quic")),li=J(io,G("quic-v1")),py=Yt(_l,li),KA=ut(_l),qA=ut(li),xl=Yt(ye,Sl,io,_l,li),dd=Yt(J(xl,G("ws"),yt(_t()))),zA=ut(dd),pd=Yt(J(xl,G("wss"),yt(_t())),J(xl,G("tls"),G("ws"),yt(_t()))),GA=ut(pd),md=J(io,G("webrtc-direct"),yt(si()),yt(si()),yt(_t())),WA=ut(md),gd=J(li,G("webtransport"),yt(si()),yt(si()),yt(_t())),jA=ut(gd),ii=Yt(dd,pd,J(Sl,yt(_t())),J(py,yt(_t())),J(ye,yt(_t())),md,gd,_t()),ZA=ut(ii),my=J(ii,G("p2p-circuit"),_t()),ao=ut(my),gy=Yt(J(ii,G("p2p-circuit"),G("webrtc"),yt(_t())),J(ii,G("webrtc"),yt(_t())),G("webrtc")),XA=ut(gy),yy=Yt(J(ye,G("tcp"),ci(),G("http"),yt(_t())),J(ye,G("http"),yt(_t()))),YA=ut(yy),wy=Yt(J(ye,G("tcp"),Yt(J(G("443"),G("http")),J(ci(),G("https"))),yt(_t())),J(ye,G("tls"),G("http"),yt(_t())),J(ye,G("https"),yt(_t()))),JA=ut(wy);var wd=ir(yd(),1),by=["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"],xy=by.map(r=>new wd.Netmask(r));function Bl(r){for(let t of xy)if(t.contains(r))return!0;return!1}function vy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ey(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Bl(o)}function Ay(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Sy(r){let t=r.split(":"),e=t[t.length-1];return Bl(e)}function _y(r){return/^::$/.test(r)||/^::1$/.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)}function ui(r){return sn(r)?Bl(r):vy(r)?Ey(r):Ay(r)?Sy(r):an(r)?_y(r):void 0}function Il(r){try{let{address:t}=r.nodeAddress();return!!ui(t)}catch{return!0}}function By(r,t){let e=Il(r.multiaddr),n=Il(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Iy(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ky(r,t){let e=ao.exactMatch(r.multiaddr),n=ao.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function un(r,t){let e=By(r,t);if(e!==0)return e;let n=ky(r,t);return n!==0?n:Iy(r,t)}var ft=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Cl=ir(xd(),1);var uo=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Tl=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},vd=r=>globalThis.DOMException===void 0?new Tl(r):new DOMException(r),Ed=r=>{let t=r.reason===void 0?vd("This operation was aborted."):r.reason;return t instanceof Error?t:vd(t)};function fo(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Ed(d)),d.addEventListener("abort",()=>{f(Ed(d))})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new uo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${e} milliseconds`,f(l))},e),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Ll(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var ho=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Ll(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var er=class extends Cl.default{#t;#e;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ho,...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.#i=t.autoStart===!1}get#b(){return this.#e||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#n===void 0){let e=this.#p-t;if(e<0)this.#s=this.#t?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},e)),!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 t=!this.#A;if(this.#b&&this.#x){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||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.#t?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}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.#u=t,this.#h()}async#S(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=fo(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#S(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof uo&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}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(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#o}get isPaused(){return this.#i}};function hi(r){let t=[Wt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Nl=60;function di(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:Wt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Wt[t.type],TTL:t.TTL??t.ttl??Nl,data:t.data instanceof Uint8Array?H(t.data):t.data}))}}var Ly=4;function Pl(r,t={}){let e=new er({concurrency:t.queryConcurrency??Ly});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),hi(o.types).forEach(a=>{s.append("type",Wt[a])}),o.onProgress?.(new ft("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=di(await a.json());return o.onProgress?.(new ft("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ad(){return[Pl("https://cloudflare-dns.com/dns-query"),Pl("https://dns.google/resolve")]}var Bd=ir(_d(),1);var Rl=class{lru;constructor(t){this.lru=(0,Bd.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return di({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Wt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Nl)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Id(r){return new Rl(r)}var Ny=1e3,pi=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Id(t.cacheSize??Ny),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ad())}async query(t,e={}){let n=hi(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new ft("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let f of u.Answer)this.cache.add(t,f);return u}catch(u){a.push(u),e.onProgress?.(new ft("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Wt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Wt||(Wt={}));function kd(r={}){return new pi(r)}var Py=32,{code:Ry}=Z("dnsaddr"),Dl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},wr=async function(t,e={}){let n=e.maxRecursiveDepth??Py;if(n===0)throw new Dl("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===Ry)??[],i=await(e?.dns??kd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Wt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ot(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Ud=ir(Md(),1),yi=Ud.default;var Vy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:wr},addressSorter:un},transportManager:{faultTolerance:Fe.FATAL_ALL}};async function Od(r){let t=yi(Vy,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return t}function Hy(r,t){try{if(typeof r=="string"&&r.length>0)return $y(r);if(typeof r=="number"&&isFinite(r))return t?.long?qy(r):Ky(r);throw new Error("Value is not a string or number.")}catch(e){let n=zy(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function $y(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\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(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var bi=Hy;function Ky(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function qy(r){let t=Math.abs(r);return t>=864e5?wi(r,t,864e5,"day"):t>=36e5?wi(r,t,36e5,"hour"):t>=6e4?wi(r,t,6e4,"minute"):t>=1e3?wi(r,t,1e3,"second"):`${r} ms`}function wi(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function zy(r){return typeof r=="object"&&r!==null&&"message"in r}function Ul(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=bi,e.destroy=u,Object.keys(r).forEach(f=>{e[f]=r[f]}),e.names=[],e.skips=[],e.formatters={};function t(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return e.colors[Math.abs(l)%e.colors.length]}e.selectColor=t;function e(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=e.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),e.formatArgs.call(y,g),(y.log||e.log).apply(y,g)}return m.namespace=f,m.useColors=e.useColors(),m.color=e.selectColor(f),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(f)),p),set:g=>{d=g}}),typeof e.init=="function"&&e.init(m),m}function n(f,l){let d=e(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){e.save(f),e.namespaces=f,e.names=[],e.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?e.skips.push(new RegExp("^"+f.substr(1)+"$")):e.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...e.names.map(a),...e.skips.map(a).map(l=>"-"+l)].join(",");return e.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=e.skips.length;l<d;l++)if(e.skips[l].test(f))return!1;for(l=0,d=e.names.length;l<d;l++)if(e.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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var xi=Jy(),Gy=["#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 Wy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function jy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+bi(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var Zy=console.debug??console.log??(()=>{});function Xy(r){try{r?xi?.setItem("debug",r):xi?.removeItem("debug")}catch{}}function Yy(){let r;try{r=xi?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Jy(){try{return localStorage}catch{}}function Qy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Fd=Ul({formatArgs:jy,save:Xy,load:Yy,useColors:Wy,setupFormatters:Qy,colors:Gy,storage:xi,log:Zy});var jt=Fd;jt.formatters.b=r=>r==null?"undefined":W.baseEncode(r);jt.formatters.t=r=>r==null?"undefined":zt.baseEncode(r);jt.formatters.m=r=>r==null?"undefined":Sc.baseEncode(r);jt.formatters.p=r=>r==null?"undefined":r.toString();jt.formatters.c=r=>r==null?"undefined":r.toString();jt.formatters.k=r=>r==null?"undefined":r.toString();jt.formatters.a=r=>r==null?"undefined":r.toString();function tw(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function vi(){return{forComponent(r){return ew(r)}}}function ew(r){let t=tw(`${r}:trace`);return jt.enabled(`${r}:trace`)&&jt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=jt(`${r}:trace`)),Object.assign(jt(r),{error:jt(`${r}:error`),trace:t})}function br(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function Ei(r){let t=ee(W.decode(`z${r}`));return nn(t)}var ce=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return br(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return br(this.map.values(),t=>t.key)}values(){return br(this.map.values(),t=>t.value)}get size(){return this.map.size}};var xr=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.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 br(this.set.entries(),t=>{let e=Ei(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Ei(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return br(this.set.values(),t=>Ei(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var qd=Symbol.for("@achingbrain/uint8arraylist");function Kd(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Si(r){return!!r?.[qd]}var wt=class r{bufs;length;[qd]=!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 e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Si(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Si(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Kd(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Kd(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Si(t))for(let n=0;n<t.length;n++)this.set(e+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,e){let{bufs:n,length:o}=this._subList(t,e);return Ft(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ft(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Si(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(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=It(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=It(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!it(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Ol=64,le=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Ol)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ct(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?it(this.fp,t.fp):!1}};function vr(r,t){return Math.floor(Math.random()*(t-r))+r}var Er=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=vr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Fl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},zd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gd=new globalThis.TextEncoder;function rw(r,t){let e=Fl[t],n=zd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function nw(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fl[t],o=zd[t],s=r;for(;s.length>0;){let i=Gd.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Vl(r,{size:t=32,utf8Buffer:e}={}){if(!Fl[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return nw(r,t,e);r=Gd.encode(r)}return rw(r,t)}var ow=ir($d(),1);var mo={hash:r=>Number(Vl(r,{size:32})),hashV:(r,t)=>sw(mo.hash(r,t))};function sw(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var iw=500,go=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??mo,this.seed=t.seed??vr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Er(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Er(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[vr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Er(this.bucketSize));for(let a=0;a<iw;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Er(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},aw={1:.5,2:.84,4:.95,8:.98};function cw(r=.001){return r>.002?2:r>1e-5?4:8}function Wd(r,t=.001){let e=cw(t),n=aw[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ol);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var _i=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??mo,this.seed=t.seed??vr(0,Math.pow(2,10)),this.filterSeries=[new go({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=P(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new go({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Hl(r,t=.001,e){return new _i({...Wd(r,t),...e??{}})}var yo;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(yo||(yo={}));var Bi=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var dn=class r{static createFromProtobuf=async t=>{let e=yo.decode(t),n=rn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=jd(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Bi("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=yo.encode({publicKey:fe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return it(this.marshal(),t.marshal())}async validate(t){let e=jd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},jd=(r,t,e)=>{let n=P(r),o=Ct(n.byteLength),s=Ct(t.length),i=Ct(e.length);return new wt(o,n,s,t,i,e)};function Zd(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var Xd="libp2p-peer-record",Yd=Uint8Array.from([3,1]);var wo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Ut((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,a={})=>{let c={multiaddr:ct(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Mt(s,n.codec()),n.decode=(s,i)=>Dt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Ut((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,s={})=>{let i={peerId:ct(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Mt(n,r.codec()),r.decode=(n,o)=>Dt(n,r.codec(),o)})(wo||(wo={}));var Ar=class r{static createFromProtobuf=t=>{let e=wo.decode(t),n=nn(ee(e.peerId)),o=(e.addresses??[]).map(i=>ot(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xd;static CODEC=Yd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=wo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!Zd(this.multiaddrs,t.multiaddrs))}};function lw(r){return r[Symbol.asyncIterator]!=null}function uw(r){if(lw(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var bo=uw;var rr={},pn=r=>{r.addEventListener("message",t=>{pn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{pn.dispatchEvent("message",r,t)})};pn.addEventListener=(r,t)=>{rr[r]==null&&(rr[r]=[]),rr[r].push(t)};pn.removeEventListener=(r,t)=>{rr[r]!=null&&(rr[r]=rr[r].filter(e=>e===t))};pn.dispatchEvent=function(r,t,e){rr[r]!=null&&rr[r].forEach(n=>n(t,e))};var $l=pn;var Kl="lock:worker:request-read",ql="lock:worker:release-read",zl="lock:master:grant-read",Gl="lock:worker:request-write",Wl="lock:worker:release-write",jl="lock:master:grant-write";var Jd=(r=21)=>Math.random().toString().substring(2);var Qd=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{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)})}}}))},tp=(r,t,e,n)=>async()=>{let o=Jd();return globalThis.postMessage({type:t,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===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},fw={singleProcess:!1},ep=r=>{if(r=Object.assign({},fw,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return $l.addEventListener("message",Qd(e,"requestReadLock",Kl,ql,zl)),$l.addEventListener("message",Qd(e,"requestWriteLock",Gl,Wl,jl)),e}return{isWorker:!0,readLock:e=>tp(e,Kl,zl,ql),writeLock:e=>tp(e,Gl,jl,Wl)}};var Sr={},nr;async function Zl(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>fo((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var hw=(r,t)=>{if(nr.isWorker===!0)return{readLock:nr.readLock(r,t),writeLock:nr.writeLock(r,t)};let e=new er({concurrency:1}),n;return{async readLock(){if(n!=null)return Zl(n,t);n=new er({concurrency:t.concurrency,autoStart:!1});let o=n,s=Zl(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Zl(e,t)}}},dw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Xl(r){let t=Object.assign({},dw,r);return nr==null&&(nr=ep(t),nr.isWorker!==!0&&(nr.addEventListener("requestReadLock",e=>{Sr[e.data.name]!=null&&Sr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),nr.addEventListener("requestWriteLock",async e=>{Sr[e.data.name]!=null&&Sr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Sr[t.name]==null&&(Sr[t.name]=hw(t.name,t)),Sr[t.name]}var mn;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ut((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,c={})=>{let u={key:"",value:ct(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ut((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),ki.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=ki.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ut((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ii.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,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ii.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new gr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Vn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Vn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Mt(o,r.codec()),r.decode=(o,s)=>Dt(o,r.codec(),s)})(mn||(mn={}));var Ii;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Ii||(Ii={}));var ki;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ki||(ki={}));function gn(r,t){let e=mn.decode(t);if(e.publicKey!=null&&r.publicKey==null){let s=rn(e.publicKey);r=ol(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:r,addresses:e.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ot(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}var Ue="/",rp=new TextEncoder().encode(Ue),Ci=rp[0],_r=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ci)throw new Error("Invalid key")}toString(t="utf8"){return H(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ue))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=rp),this._buf[0]!==Ci){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ci,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ci;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Ue).slice(1)}type(){return pw(this.baseNamespace())}name(){return mw(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ue)||(t+=Ue),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ue):new r(t.slice(0,-1).join(Ue))}child(t){return this.toString()===Ue?t:t.toString()===Ue?this:new r(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 r.withNamespaces([...this.namespaces(),...gw(t.map(e=>e.namespaces()))])}};function pw(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function mw(r){let t=r.split(":");return t[t.length-1]}function gw(r){return[].concat(...r)}var Yl="/peers/";function yn(r){if(!No(r)||r.type==null)throw new D("Invalid PeerId");let t=r.toCID().toString();return new _r(`${Yl}${t}`)}async function np(r,t,e){let n=new Map;for(let o of e){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ot(o.multiaddr)),!tr(o.multiaddr))throw new D("Multiaddr was invalid");if(!await t(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 Li(r,t,e,n){if(t==null)throw new D("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Ti(d,{validate:op})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ti(d,{validate:sp,map:ip})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ti([...a.entries()],{validate:op})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ti([...h.entries()],{validate:sp,map:ip})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=fe(o.id.publicKey):t.publicKey!=null?f=fe(t.publicKey):r.publicKey!=null&&(f=fe(r.publicKey));let l={addresses:await np(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ti(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function op(r,t){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function sp(r,t){if(typeof r!="string")throw new D("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new D("Tag value must be an integer");if(t.value<0||t.value>100)throw new D("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new D("Tag ttl must be an integer");if(t.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function ip(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Ni(r,t,e){let n=r.toString().split("/")[2],o=pt.parse(n,zt),s=ti(o),i=e.get(s);if(i!=null)return i;let a=gn(s,t);return e.set(s,a),a}function yw(r,t){return r==null?{}:{prefix:Yl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Ni(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Ni(n.key,n.value,t),Ni(o.key,o.value,t)))}}var Pi=class{peerId;datastore;lock;addressFilter;constructor(t,e={}){this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=Xl({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(yn(t))}async delete(t){if(this.peerId.equals(t))throw new D("Cannot delete self peer");await this.datastore.delete(yn(t))}async load(t){let e=await this.datastore.get(yn(t));return gn(t,e)}async save(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Li(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,s,n,o)}async patch(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Li(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async merge(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Li(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async*all(t){let e=new ce;for await(let{key:n,value:o}of this.datastore.query(yw(t??{},e))){let s=Ni(n,o,e);s.id.equals(this.peerId)||(yield s)}}async#t(t){try{let e=await this.datastore.get(yn(t)),n=gn(t,e);return{existingBuf:e,existingPeer:n}}catch(e){if(e.name!=="NotFoundError")throw e}return{}}async#e(t,e,n,o){let s=mn.encode(e);return n!=null&&it(s,n)?{peer:gn(t,s),previous:o,updated:!1}:(await this.datastore.put(yn(t),s),{peer:gn(t,s),previous:o,updated:!0})}};var Jl=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Pi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){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(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await bo(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=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"),e()}}async has(t){this.log.trace("has await read lock");let e=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"),e()}}async get(t){this.log.trace("get await read lock");let e=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"),e()}}async save(t,e){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(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){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(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){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(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await dn.openAndCertify(t,Ar.DOMAIN),o=ti(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=Ar.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await dn.createFromProtobuf(i.peerRecordEnvelope),c=Ar.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function ap(r,t={}){return new Jl(r,t)}var Ri=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function ww(r){return r[Symbol.asyncIterator]!=null}function bw(r){if(ww(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Ql=bw;function xw(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var cp=xw;function vw(r){return r[Symbol.asyncIterator]!=null}function Ew(r,t){let e=0;if(vw(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=cp(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var Br=Ew;function Aw(r){return r[Symbol.asyncIterator]!=null}function Sw(r,t){return Aw(r)?async function*(){yield*(await bo(r)).sort(t)}():function*(){yield*bo(r).sort(t)}()}var tu=Sw;function _w(r){return r[Symbol.asyncIterator]!=null}function Bw(r,t){return _w(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var eu=Bw;var Di=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await Ql(this.putMany(t,n)),t=[],await Ql(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=Br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tu(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=Br(n,()=>o++>=s)}return t.limit!=null&&(n=eu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=Br(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tu(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=Br(n,()=>s++>=o)}return t.limit!=null&&(n=eu(n,t.limit)),n}};var Mi=class extends Di{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new Ri;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new _r(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new _r(t)}};function lp(r,t){let e;return function(){let n=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(n,t)}}var Iw=r=>r;function ru(r,t){let e=r.getPeerId();return e!=null&&ge(e).equals(t)&&(r=r.decapsulate(ot(`/p2p/${t.toString()}`))),r}var Ui=class{log;components;listen;announce;observed;announceFilter;constructor(t,e={}){let{listen:n=[],announce:o=[]}=e;this.components=t,this.log=t.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=e.announceFilter??Iw,this._updatePeerStoreAddresses=lp(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([e,n])=>n.confident).map(([e])=>ot(e))).map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>ot(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>ot(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>ot(t))}addObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString();this.observed.has(e)||this.observed.set(e,{confident:!1})}confirmObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString(),o=(this.observed.get(e)??{confident:!1}).confident;this.observed.set(e,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString();this.observed.delete(e)}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,o])=>o.confident).map(([n])=>n));let e=new Set(t);return this.announceFilter(Array.from(e).map(n=>ot(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var up;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(up||(up={}));var Oi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Fi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},xo=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},vo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Vi=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Hi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},$i=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Eo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Ir=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Ki=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},qi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},kr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Ao=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},zi=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var nu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=vi())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>$o(e)).map(async e=>{await e[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")}},Cw=["metrics","connectionProtector","dns"],Tw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function fp(r={}){let t=new nu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Tw.includes(o)){let i=t.components[o];if(i==null&&!Cw.includes(o))throw new Oi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function hp(r){let t={};for(let e of Object.values(r.components))for(let n of Lw(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Nw(e))if(t[n]!==!0)throw new Fi(`Service "${Pw(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Lw(r){return Array.isArray(r?.[Bn])?r[Bn]:[]}function Nw(r){return Array.isArray(r?.[Ra])?r[Ra]:[]}function Pw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function dp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{let e=t.stringTuples();return e[0][0]===4||e[0][0]===41?!!ui(`${e[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 pp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rw=new WeakMap;function Dw({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(pp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(pp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Rw.set(l,()=>{c(s),s=null,i()}),l}}var Mw=Dw(),mp=Mw;var Gi=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}};var Wi=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 ou}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Gi("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 mp(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}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)}},ou=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function ji(r){if(No(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:ge(e),r.forEach(n=>{if(!tr(n))throw new Pr("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=ge(o);if(t?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Uw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function gp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Uw;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var yp="last-dial-failure",wp="last-dial-success";var Zi=100,Xi=50;var bp={maxConnections:Zi,allow:[]},Yi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??bp.maxConnections,this.allow=e.allow??bp.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(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new ce;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];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()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await gp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ji=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}},wn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ji(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 e=this.head;this.head=e.next=new Ji(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var su=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Qi(r={}){return Ow(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ow(r,t){t=t??{};let e=t.onEnd,n=new wn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new wn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;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=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new wn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new su)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(g){return m.end(g),e!=null&&(e(g),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var iu=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function bn(r,t,e,n){let o=new iu(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ta=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function or(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ta(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ta(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ea=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new be)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ra=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Fw(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,tt(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new be),this.cleanup())}async join(t={}){let e=new ea(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await or(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var xn=class extends ve{concurrency;queue;pending;sort;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.sort=t.sort,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 e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){e?.signal?.throwIfAborted();let n=new ra(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new be)}),this.clear()}async onEmpty(t){this.size!==0&&await bn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await bn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await bn(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 e=Qi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new be("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var na=class extends xn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Oe(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}async function xp(r,t){let e=!1;for(let o of ln.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}var So={addressSorter:un,maxParallelDials:Xi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:wr}},oa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter??So.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??So.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??So.maxDialQueueLength,this.dialTimeout=e.dialTimeout??So.dialTimeout,this.connections=e.connections??new ce,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,tt(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(e.resolvers??{}))ln.set(n,o);this.queue=new na({concurrency:e.maxParallelDials??So.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,tt(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=ji(t),s=Array.from(this.connections.values()).flat().find(a=>e.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),e.onProgress?.(new ft("dial-queue:already-connected")),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 e.onProgress?.(new ft("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Rr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new ft("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new ft("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new ft("dial-queue:calculated-addresses",u)),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 d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Rr("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[wp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[yp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Fo(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:e.priority??uu,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal,onProgress:e.onProgress})}createDialAbortController(t){let e=Oe([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,t]);return tt(1/0,e),e}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(l=>({multiaddr:ot(l),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Rr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Eo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let l=await this.components.peerStore.get(t);o.push(...l.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let l=await this.components.peerRouting.findPeer(t);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",t,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await xp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(t!=null){let l=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Ir("The dial request has 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 Eo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!ao.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var sa=class extends xn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Ip=ir(_p(),1);var Hw=Object.prototype.toString,$w=r=>Hw.call(r)==="[object Error]",Kw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function fu(r){return r&&$w(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Kw.has(r.message):!1}var hu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},Bp=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function du(r,t){return new Promise((e,n)=>{t={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...t};let o=Ip.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof hu)throw c.originalError;if(c instanceof TypeError&&!fu(c))throw c;if(Bp(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Bp(u,a,t),i(),n(u)}}})})}var ia=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new sa({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,t.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(t){!this.started||!(await this.peerStore.get(t)).tags.has(Pa)||this.queue.has(t)||this.queue.add(async n=>{await du(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(n=>{this.log.error("failed to reconnect to %p",t,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(Pa)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};var uu=50,pu={maxConnections:Zi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},aa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(t,e={}){if(this.maxConnections=e.maxConnections??pu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new ce,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=(e.allow??[]).map(n=>ot(n)),this.deny=(e.deny??[]).map(n=>ot(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??pu.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Wi({points:e.inboundConnectionThreshold??pu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Yi({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new oa(t,{addressSorter:e.addressSorter??un,maxParallelDials:e.maxParallelDials??Xi,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??5e3,resolvers:e.resolvers??{dnsaddr:wr},connections:this.connections}),this.reconnectQueue=new ia({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0};for(let e of this.connections.values())for(let n of e)n.direction==="inbound"?t.inbound++:t.outbound++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??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 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))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),await Du(this.dialQueue,this.reconnectQueue),this.started=!0,this.log("started")}async stop(){await Mu(this.reconnectQueue,this.dialQueue);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}let n=e.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(e):(s=!0,this.connections.set(n,[e])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t;if(!this.started)return;let n=e.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==e.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.isStarted())throw new xe("Not started");e.signal?.throwIfAborted();let{peerId:n}=ji(t);if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new ft("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??uu}),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(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.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",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!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(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>ot(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var vn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(t){this.timespan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timespan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var Gw=1.2,Ww=2,jw=2e3,ca=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new vn(t.interval??5e3),this.failure=new vn(t.interval??5e3),this.next=new vn(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Ww,this.timeoutMultiplier=t.timeoutMultiplier??Gw,this.minTimeout=t.minTimeout??jw,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=Oe([t.signal,n]);return tt(1/0,o,n),o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var mu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),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,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=lt(),await or(this.readNext.promise,e?.signal,e)}};function kp(){return new mu}var la=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var gu=class extends Error{code;constructor(t,e){super(t),this.code=e}},yu=class extends gu{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function ua(r,t){let e=kp();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.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 wt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new yu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new wt:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new la("unexpected end of input");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 e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Zw=1e4,Xw="1.0.0",Yw="ping",Jw="ipfs",Cp=32,Qw=!0,fa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Jw}/${Yw}/${Xw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Zw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Qw,this.timeout=new ca({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Bn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,tt(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ua(o);e=Date.now(),await Promise.all([s.write(tn(Cp),{signal:n}),s.read(Cp,{signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function tb(r){return r[Symbol.asyncIterator]!=null}function eb(...r){let t=[];for(let e of r)tb(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Qi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var _o=eb;var ha=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new xo("No content routers available");let n=this,o=new xr;for await(let s of _o(...n.routers.map(i=>i.findProviders(t,e))))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(t,e={}){if(this.routers.length===0)throw new xo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new xe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new xe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var da=globalThis.CustomEvent??Event;async function*wu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=lt(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new da("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new da("task-complete"))})}c=!0,o.dispatchEvent(new da("task-complete"))}catch(p){u=p,o.dispatchEvent(new da("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=lt(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var pa=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new vo("No peer routers available");if(t.toString()===this.peerId.toString())throw new Vi("Should not try to find self");let n=this,o=_o(...this.routers.map(s=>async function*(){try{yield await s.findPeer(t,e)}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 Do}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new vo("No peer routers available");let n=this,o=Hl(1024);for await(let s of wu(async function*(){let i=_o(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,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.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ma=class extends ve{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,tt(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,tt(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Oe([this.shutdownController.signal,t?.signal]);tt(1/0,e);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await bn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,tt(1/0,this.walkController.signal);let t=Oe([this.walkController.signal,this.shutdownController.signal]);tt(1/0,t);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await or(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var bu=32,xu=64,ga=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Hi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t))throw new $i(`Handler already registered for protocol ${t}`);let o=yi.bind({ignoreUndefined:!0})({maxInboundStreams:bu,maxOutboundStreams:xu},n);this.handlers.set(t,{handler:e,options:o}),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,e){if(e==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var vu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Tp(r){let{name:t,metrics:e}=r,n;return e!=null?n=new vu({name:t,metrics:e}):n=new Map,n}var ya=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=Tp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Fe.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new D("Transport must have a valid tag");if(this.transports.has(e))throw new D(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}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[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new zi(`No transport available for address ${String(t)}`);return e?.onProgress?.(new ft("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new xe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(t),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 d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){e.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Fe.NO_FATAL)throw new Ir(`Transport (${n}) could not listen on any available address`)}if(e.length===this.transports.size){let n=`no valid addresses were provided for transports [${e.join(", ")}]`;if(this.faultTolerance===Fe.FATAL_ALL)throw new Ir(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var Bt="/multistream/1.0.0";var wa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ba=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Bo(r,t={}){let e=ua(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ht(t.maxDataLength));let n=t?.lengthDecoder??se,o=t?.lengthEncoder??Ct;return{read:async i=>{let a=-1,c=new wt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new wa("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new xa("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ba("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new wt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new wt(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var rb=P(`
7
- `);async function Tr(r,t,e){await r.write(t,e)}async function Lp(r,t,e){await r.writeV(t,e)}async function nb(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==rb[0])throw t.log.error("Invalid mss message - missing newline",e),new Oo("Missing newline");return e.sublist(0,-1)}async function sr(r,t){let e=await nb(r,t);return H(e.subarray())}async function Io(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return ob(r,t[0],e);let n=Bo(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',Bt,o);let s=P(`${Bt}
4
+ `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
+ ${e.join(`
6
+ `)}`:`${t} :`}};Zf=Qt;C.Constructed=Zf;Qt.NAME="CONSTRUCTED";var ys=class extends Le{fromBER(e,t,n){return t}toBER(e){return ct}};ys.override="EndOfContentValueBlock";var Xf,ws=class extends Se{constructor(e={}){super(e,ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Xf=ws;C.EndOfContent=Xf;ws.NAME=zn;var Yf,Yr=class extends Se{constructor(e={}){super(e,Le),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}`}};Yf=Yr;C.Null=Yf;Yr.NAME="NULL";var bs=class extends Pt(Le){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.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=q.BufferSourceConverter.toUint8Array(e);return Nt(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,jc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};bs.NAME="BooleanValueBlock";var Jf,xs=class extends Se{constructor(e={}){super(e,bs),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}`}};Jf=xs;C.Boolean=Jf;xs.NAME="BOOLEAN";var vs=class extends Pt(pt){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=pt.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===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==zf)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?pt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};vs.NAME="OctetStringValueBlock";var Qf,Es=class r extends Se{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},vs),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=Xs(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?Qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.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 q.BufferSourceConverter.concat(e)}};Qf=Es;C.OctetString=Qf;Es.NAME=zf;var As=class extends Pt(pt){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=pt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===zn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Gf)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=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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=Xs(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 pt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ct;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}}};As.NAME="BitStringValueBlock";var eh,Jr=class extends Se{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},As),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 Qt.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)}`}}};eh=Jr;C.BitString=eh;Jr.NAME=Gf;var th;function C0(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 d=f;d>=0;d--,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=us(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=us(t,s)),s}function qf(r){if(r>=Kn.length)for(let e=Kn.length;e<=r;e++){let t=new Uint8Array([0]),n=Kn[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=us(t,n)),Kn.push(n)}return Kn[r]}function T0(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 Gn=class extends Pt(Le){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=jc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Hf(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=T0(qf(n),t),i="-";break;default:t=C0(t,qf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Kf.charAt(t[c]));return a===!1&&(i+=Kf.charAt(0)),i}};th=Gn;Gn.NAME="IntegerValueBlock";Object.defineProperty(th.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var rh,_e=class r extends Se{constructor(e={}){super(e,Gn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return fs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){fs();let t=BigInt(e),n=new qn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.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()}`}};rh=_e;C.Integer=rh;_e.NAME="INTEGER";var nh,Ss=class extends _e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};nh=Ss;C.Enumerated=nh;Ss.NAME="ENUMERATED";var Wn=class extends Pt(Le){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=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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=wr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){fs();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=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;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=q.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}}};Wn.NAME="sidBlock";var _s=class extends Le{constructor({value:e=en,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;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,ct;t.push(o)}return Zc(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 Wn;if(o>Number.MAX_SAFE_INTEGER){fs();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}};_s.NAME="ObjectIdentifierValueBlock";var oh,Qr=class extends Se{constructor(e={}){super(e,_s),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()}}};oh=Qr;C.ObjectIdentifier=oh;Qr.NAME="OBJECT IDENTIFIER";var jn=class extends Pt(Ct){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Nt(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=wr(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=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ct;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=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var Bs=class extends Le{constructor({value:e=en,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;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,ct;n.push(s)}return Zc(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 jn;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}};Bs.NAME="RelativeObjectIdentifierValueBlock";var sh,Is=class extends Se{constructor(e={}){super(e,Bs),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()}}};sh=Is;C.RelativeObjectIdentifier=sh;Is.NAME="RelativeObjectIdentifier";var ih,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ih=Tt;C.Sequence=ih;Tt.NAME="SEQUENCE";var ah,ks=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ah=ks;C.Set=ah;ks.NAME="SET";var Cs=class extends Pt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=en}toJSON(){return{...super.toJSON(),value:this.value}}};Cs.NAME="StringValueBlock";var Ts=class extends Cs{};Ts.NAME="SimpleStringValueBlock";var Oe=class extends ps{constructor({...e}={}){super(e,Ts)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.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}};Oe.NAME="SIMPLE STRING";var Ls=class extends Oe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ls.NAME="Utf8StringValueBlock";var ch,Lt=class extends Ls{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};ch=Lt;C.Utf8String=ch;Lt.NAME="UTF8String";var Ns=class extends Oe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ns.NAME="BmpStringValueBlock";var lh,Ps=class extends Ns{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};lh=Ps;C.BmpString=lh;Ps.NAME="BMPString";var Rs=class extends Oe{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=Jt(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}};Rs.NAME="UniversalStringValueBlock";var uh,Ds=class extends Rs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};uh=Ds;C.UniversalString=uh;Ds.NAME="UniversalString";var fh,Ms=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};fh=Ms;C.NumericString=fh;Ms.NAME="NumericString";var hh,Us=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};hh=Us;C.PrintableString=hh;Us.NAME="PrintableString";var dh,Os=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};dh=Os;C.TeletexString=dh;Os.NAME="TeletexString";var ph,Fs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};ph=Fs;C.VideotexString=ph;Fs.NAME="VideotexString";var mh,Vs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};mh=Vs;C.IA5String=mh;Vs.NAME="IA5String";var gh,Hs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};gh=Hs;C.GraphicString=gh;Hs.NAME="GraphicString";var yh,Zn=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};yh=Zn;C.VisibleString=yh;Zn.NAME="VisibleString";var wh,$s=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};wh=$s;C.GeneralString=wh;$s.NAME="GeneralString";var bh,Ks=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};bh=Ks;C.CharacterString=bh;Ks.NAME="CharacterString";var xh,Xn=class extends Zn{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,q.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]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(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}}};xh=Xn;C.UTCTime=xh;Xn.NAME="UTCTime";var vh,qs=class extends Xn{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,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}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(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};vh=qs;C.GeneralizedTime=vh;qs.NAME="GeneralizedTime";var Eh,zs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Eh=zs;C.DATE=Eh;zs.NAME="DATE";var Ah,Gs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Ah=Gs;C.TimeOfDay=Ah;Gs.NAME="TimeOfDay";var Sh,Ws=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Sh=Ws;C.DateTime=Sh;Ws.NAME="DateTime";var _h,js=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};_h=js;C.Duration=_h;js.NAME="Duration";var Bh,Zs=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Bh=Zs;C.TIME=Bh;Zs.NAME="TIME";function H(r,e="utf8"){let t=ss[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function tn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return qr(r)}var Yn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Jn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ys=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ih={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ys("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");return e}};var er=Ih;async function kh(r){let e=await er.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 N0(e);return{privateKey:t[0],publicKey:t[1]}}async function Ch(r,e){let t=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await er.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Th(r,e,t){let n=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return er.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function N0(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([er.get().subtle.exportKey("jwk",r.privateKey),er.get().subtle.exportKey("jwk",r.publicKey)])}function Jc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var rn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return Th(this._key,t,e)}},eo=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Qn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Ch(this._key,e)}};var Js=8192,Qc=18;function Lh(r){let{result:e}=Yc(r),t=e.valueBlock.value;return{n:H(mt(t[1].toBigInt()),"base64url"),e:H(mt(t[2].toBigInt()),"base64url"),d:H(mt(t[3].toBigInt()),"base64url"),p:H(mt(t[4].toBigInt()),"base64url"),q:H(mt(t[5].toBigInt()),"base64url"),dp:H(mt(t[6].toBigInt()),"base64url"),dq:H(mt(t[7].toBigInt()),"base64url"),qi:H(mt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function P0(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 D("JWK was missing components");let t=new Tt({value:[new _e({value:0}),_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url"))),_e.fromBigInt(gt(P(r.d,"base64url"))),_e.fromBigInt(gt(P(r.p,"base64url"))),_e.fromBigInt(gt(P(r.q,"base64url"))),_e.fromBigInt(gt(P(r.dp,"base64url"))),_e.fromBigInt(gt(P(r.dq,"base64url"))),_e.fromBigInt(gt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Nh(r){let{result:e}=Yc(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(mt(t[0].toBigInt()),"base64url"),e:H(mt(t[1].toBigInt()),"base64url")}}function el(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new Qr({value:"1.2.840.113549.1.1.1"}),new Yr]}),new Jr({valueHex:new Tt({value:[_e.fromBigInt(gt(P(r.n,"base64url"))),_e.fromBigInt(gt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function mt(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 gt(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(""))}function Ph(r){let e=Lh(r);return Rh(e)}function tl(r){let e=Nh(r);if(Jc(e)>Js)throw new Rr("Key size is too large");let t=Zr(dt.encode({Type:we.RSA,Data:r})),n=tt(Qc,t);return new rn(e,n)}function Rh(r){if(Jc(r)>Js)throw new D("Key size is too large");let e=Dh(r),t=Zr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new rn(e.publicKey,n))}async function rl(r){if(r>Js)throw new D("Key size is too large");let e=await kh(r),t=Zr(dt.encode({Type:we.RSA,Data:el(e.publicKey)})),n=tt(Qc,t);return new eo(e.privateKey,new rn(e.publicKey,n))}function Dh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Qs=class extends Kr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,rf(e);let n=Pn(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 $r(this),this.iHash.update(e),this}digestInto(e){$r(this),Hr(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()}},nl=(r,e,t)=>new Qs(r,e).update(t).digest();nl.create=(r,e)=>new Qs(r,e);function Mh(r){r.lowS!==void 0&&ot("lowS",r.lowS),r.prehash!==void 0&&ot("prehash",r.prehash)}function R0(r){let e=Mn(r);ft(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:D0,hexToBytes:M0}=Zo,Rt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Rt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=lr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?lr(o.length/2|128):"";return`${lr(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Rt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Rt;if(r<Dt)throw new e("integer: negative integers are not allowed");let t=lr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Rt;if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return D0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Rt,o=typeof r=="string"?M0(r):r;Gr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Rt,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Dt=BigInt(0),Ee=BigInt(1),r2=BigInt(2),Uh=BigInt(3),n2=BigInt(4);function U0(r){let e=R0(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return It(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Rn(m,Ee,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(zt(m)&&(m=_t(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Bt(le("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=J(x,w)),$e("private key",x,Ee,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=hr((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let A=t.mul(y,g),_=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=hr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(le("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Jo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(y,_),t.mul(x,w)),B=t.eql(t.mul(b,_),t.mul(A,w));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,Uh),{px:w,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,T=t.mul(w,w),re=t.mul(x,x),V=t.mul(A,A),F=t.mul(w,x);return F=t.add(F,F),B=t.mul(w,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,V),v=t.add(_,v),_=t.sub(re,v),v=t.add(re,v),v=t.mul(_,v),_=t.mul(F,_),B=t.mul(b,B),V=t.mul(g,V),F=t.sub(T,V),F=t.mul(g,F),F=t.add(F,B),B=t.add(T,T),T=t.add(B,T),T=t.add(T,V),T=t.mul(T,F),v=t.add(v,T),V=t.mul(x,A),V=t.add(V,V),T=t.mul(V,F),_=t.sub(_,T),B=t.mul(V,re),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,T=t.ZERO,re=e.a,V=t.mul(e.b,Uh),F=t.mul(y,x),R=t.mul(b,A),k=t.mul(w,_),L=t.add(y,b),S=t.add(x,A);L=t.mul(L,S),S=t.add(F,R),L=t.sub(L,S),S=t.add(y,w);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(F,k),S=t.sub(S,E),E=t.add(b,w),v=t.add(A,_),E=t.mul(E,v),v=t.add(R,k),E=t.sub(E,v),T=t.mul(re,S),v=t.mul(V,k),T=t.add(v,T),v=t.sub(R,T),T=t.add(R,T),B=t.mul(v,T),R=t.add(F,F),R=t.add(R,F),k=t.mul(re,k),S=t.mul(V,S),R=t.add(R,k),k=t.sub(F,k),k=t.mul(re,k),S=t.add(S,k),F=t.mul(R,S),B=t.add(B,F),F=t.mul(E,S),v=t.mul(L,v),v=t.sub(v,F),F=t.mul(L,R),T=t.mul(E,T),T=t.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$e("scalar",g,Dt,e.n);let y=d.ZERO;if(g===Dt)return y;if(g===Ee)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Dt||_>Dt;)x&Ee&&(v=v.add(T)),_&Ee&&(B=B.add(T)),T=T.double(),x>>=Ee,_>>=Ee;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(t.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=e;$e("scalar",g,Ee,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:re}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(t.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=re.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Dt||v===Ee||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===Ee)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===Ee?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return ot("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return ot("isCompressed",g),_t(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Yo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function O0(r){let e=Mn(r);return ft(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Oh(r){let e=O0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(k){return J(k,n)}function a(k){return Xo(k,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=U0({...e,toBytes(k,L,S){let E=L.toAffine(),I=t.toBytes(E.x),N=It;return ot("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),I):N(Uint8Array.from([4]),I,t.toBytes(E.y))},fromBytes(k){let L=k.length,S=k[0],E=k.subarray(1);if(L===o&&(S===2||S===3)){let I=Bt(E);if(!Rn(I,Ee,t.ORDER))throw new Error("Point is not on curve");let N=f(I),M;try{M=t.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&Ee)===Ee;return(S&1)===1!==U&&(M=t.neg(M)),{x:I,y:M}}else if(L===s&&S===4){let I=t.fromBytes(E.subarray(0,t.BYTES)),N=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:I,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=k=>_t(Wt(k,e.nByteLength));function h(k){let L=n>>Ee;return k>L}function p(k){return h(k)?i(-k):k}let m=(k,L,S)=>Bt(k.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=e.nByteLength;return L=le("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=Rt.toSig(le("DER",L));return new g(S,E)}assertValidity(){$e("r",this.r,Ee,n),$e("s",this.s,Ee,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:I}=this,N=_(le("msgHash",L));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let M=I===2||I===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=I&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),Y=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,Y);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return ur(this.toDERHex())}toDERHex(){return Rt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ur(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(k){try{return u(k),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let k=ac(e.n);return gf(e.randomBytes(k),e.n)},precompute(k=8,L=c.BASE){return L._setWindowSize(k),L.multiply(BigInt(3)),L}};function b(k,L=!0){return c.fromPrivateKey(k).toRawBytes(L)}function w(k){let L=zt(k),S=typeof k=="string",E=(L||S)&&k.length;return L?E===o||E===s:S?E===2*o||E===2*s:k instanceof c}function x(k,L,S=!0){if(w(k))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(k)).toRawBytes(S)}let A=e.bits2int||function(k){let L=Bt(k),S=k.length*8-e.nBitLength;return S>0?L>>BigInt(S):L},_=e.bits2int_modN||function(k){return i(A(k))},v=Dn(e.nBitLength);function B(k){return $e(`num < 2^${e.nBitLength}`,k,Dt,v),Wt(k,e.nByteLength)}function T(k,L,S=re){if(["recovered","canonical"].some(ve=>ve in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:I}=e,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),k=le("msgHash",k),Mh(S),M&&(k=le("prehashed msgHash",E(k)));let $=_(k),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let ve=U===!0?I(t.BYTES):U;K.push(le("extraEntropy",ve))}let Y=It(...K),Q=$;function xe(ve){let Ae=A(ve);if(!l(Ae))return;let Pe=a(Ae),me=c.BASE.multiply(Ae).toAffine(),He=i(me.x);if(He===Dt)return;let wt=i(Pe*i(Q+He*z));if(wt===Dt)return;let An=(me.x===He?0:2)|Number(me.y&Ee),Sn=wt;return N&&h(wt)&&(Sn=p(wt),An^=1),new g(He,Sn,An)}return{seed:Y,k2sig:xe}}let re={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function F(k,L,S=re){let{seed:E,k2sig:I}=T(k,L,S),N=e;return nc(N.hash.outputLen,N.nByteLength,N.hmac)(E,I)}c.BASE._setWindowSize(8);function R(k,L,S,E=V){let I=k;if(L=le("msgHash",L),S=le("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");Mh(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof I=="string"||zt(I))try{U=g.fromDER(I)}catch(me){if(!(me instanceof Rt.Err))throw me;U=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:me,s:He}=I;U=new g(me,He)}else throw new Error("PARSE");$=c.fromHex(S)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=e.hash(L));let{r:z,s:K}=U,Y=_(L),Q=a(K),xe=i(Y*Q),ve=i(z*Q),Ae=c.BASE.multiplyAndAddUnsafe($,xe,ve)?.toAffine();return Ae?i(Ae.x)===z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function F0(r){return{hash:r,hmac:(e,...t)=>nl(r,e,Za(...t)),randomBytes:qr}}function Fh(r,e){let t=n=>Oh({...r,...F0(n)});return Object.freeze({...t(e),create:t})}var $h=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Vh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),V0=BigInt(1),ol=BigInt(2),Hh=(r,e)=>(r+e/ol)/e;function H0(r){let e=$h,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=oe(f,t,e)*f%e,d=oe(l,t,e)*f%e,h=oe(d,ol,e)*u%e,p=oe(h,o,e)*h%e,m=oe(p,s,e)*p%e,g=oe(m,a,e)*m%e,y=oe(g,c,e)*g%e,b=oe(y,a,e)*m%e,w=oe(b,t,e)*f%e,x=oe(w,i,e)*p%e,A=oe(x,n,e)*u%e,_=oe(A,ol,e);if(!sl.eql(sl.sqr(_),r))throw new Error("Cannot find square root");return _}var sl=jt($h,void 0,void 0,{sqrt:H0}),Ye=Fh({a:BigInt(0),b:BigInt(7),Fp:sl,n:Vh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Vh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-V0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Hh(s*r,e),c=Hh(-n*r,e),u=J(r-a*t-c*o,e),f=J(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Zr),h2=BigInt(0);var d2=Ye.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Kh(r,e){let t=Wr.digest(e instanceof Uint8Array?e:e.subarray());if(il(t))return t.then(({digest:n})=>Ye.sign(n,r).toDERRawBytes()).catch(n=>{throw new Yn(String(n))});try{return Ye.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Yn(String(n))}}function qh(r,e,t){let n=Wr.digest(t instanceof Uint8Array?t:t.subarray());if(il(n))return n.then(({digest:o})=>Ye.verify(e,o,r)).catch(o=>{throw new Jn(String(o))});try{return Ye.verify(e,n.digest,r)}catch(o){throw new Jn(String(o))}}var to=class{type="secp256k1";raw;_key;constructor(e){this._key=Wh(e),this.raw=zh(this._key)}toMultihash(){return At.digest(ht(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return qh(this._key,t,e)}},ei=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Gh(e),this.publicKey=new to(t??jh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Kh(this.raw,e)}};function al(r){return new to(r)}async function Zh(){let r=$0();return new ei(r)}function zh(r){return Ye.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Gh(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new _n(String(e))}}function Wh(r){try{return Ye.ProjectivePoint.fromHex(r),r}catch(e){throw new Rr(String(e))}}function jh(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new _n(String(e))}}function $0(){return Ye.utils.randomPrivateKey()}async function Xh(r,e){if(r==="Ed25519")return _f();if(r==="secp256k1")return Zh();if(r==="RSA")return rl(e??2048);throw new Ht}function nn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case we.RSA:return tl(n);case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function Yh(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case we.Ed25519:return hc(n);case we.secp256k1:return al(n);default:throw new Ht}}function ht(r){return dt.encode({Type:we[r.type],Data:r.raw})}var Jh=Symbol.for("nodejs.util.inspect.custom"),K0=114,ro=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[No]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(K0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jh](){return`PeerId(${this.toString()})`}},no=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},oo=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},so=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},q0=2336,io=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(P(this.url))}[Jh](){return`PeerId(${this.url})`}[No]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(q0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var z0=114,Qh=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=rt(W.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=rt(e.decode(r))}return on(t)}function cl(r){if(r.type==="Ed25519")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new so({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new no({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function ed(r){return cl(r.publicKey)}function on(r){if(W0(r))return new no({multihash:r});if(G0(r))try{let e=Yh(r);if(e.type==="Ed25519")return new oo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new so({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new io(new URL(t))}throw new Oo("Supplied PeerID Multihash is invalid")}function ti(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==z0&&r.code!==Qh)throw new Uo("Supplied PeerID CID is invalid");if(r.code===Qh){let e=H(r.multihash.digest);return new io(new URL(e))}return on(r.multihash)}function G0(r){return r.code===At.code}function W0(r){return r.code===Wr.code}var ri=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 d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});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 td=45,j0=15,sn=new ri;function ll(r){if(!(r.length>j0))return sn.new(r).parseWith(()=>sn.readIPv4Addr())}function ul(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>td))return sn.new(r).parseWith(()=>sn.readIPv6Addr())}function ni(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>td))return sn.new(r).parseWith(()=>sn.readIPAddr())}function an(r){return!!ll(r)}function cn(r){return!!ul(r)}function oi(r){return!!ni(r)}var EE=parseInt("0xFFFF",16),AE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var od=an,Q0=cn,fl=function(r){let e=0;if(r=r.toString().trim(),od(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Q0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=od(t[n]),i;s&&(i=fl(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(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")},sd=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 ln={},hl={},ty=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];ty.forEach(r=>{let e=ry(...r);hl[e.code]=e,ln[e.name]=e});function ry(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(hl[r]!=null)return hl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ln[r]!=null)return ln[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var oA=X("ip4"),sA=X("ip6"),iA=X("ipcidr");function gl(r,e){switch(X(r).code){case 4:case 41:return oy(e);case 42:return ml(e);case 6:case 273:case 33:case 132:return cd(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ml(e);case 421:return cy(e);case 444:return ad(e);case 445:return ad(e);case 466:return ay(e);case 481:return globalThis.encodeURIComponent(ml(e));default:return H(e,"base16")}}function yl(r,e){switch(X(r).code){case 4:return id(e);case 41:return id(e);case 42:return pl(e);case 6:case 273:case 33:case 132:return wl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return pl(e);case 421:return sy(e);case 444:return ly(e);case 445:return uy(e);case 466:return iy(e);case 481:return pl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var dl=Object.values(Fn).map(r=>r.decoder),ny=function(){let r=dl[0].or(dl[1]);return dl.slice(2).forEach(e=>r=r.or(e)),r}();function id(r){if(!oi(r))throw new Error("invalid ip address");return fl(r)}function oy(r){let e=sd(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!oi(e))throw new Error("invalid ip address");return e}function wl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function cd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function pl(r){let e=P(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function ml(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function sy(r){let e;r[0]==="Q"||r[0]==="1"?e=rt(W.decode(`z${r}`)).bytes:e=ge.parse(r).multihash.bytes;let t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function iy(r){let e=ny.decode(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function ay(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function cy(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function ly(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=We.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=wl(n);return Fe([t,o],t.length+o.length)}function uy(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=We.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=wl(n);return Fe([t,o],t.length+o.length)}function ad(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=cd(t);return`${n}:${o}`}function ld(r){r=bl(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=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw fd("invalid address: "+r);if(a.path===!0){n=bl(o.slice(s).join("/")),e.push([a.code,yl(a.code,n)]),t.push([a.code,n]);break}let c=yl(a.code,o[s]);e.push([a.code,c]),t.push([a.code,gl(a.code,c)])}return{string:ud(t),bytes:vl(e),tuples:e,stringTuples:t,path:n}}function xl(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=X(s),c=fy(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 fd("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=gl(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:ud(t),tuples:e,stringTuples:t,path:n}}function ud(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),bl(e.join("/"))}function vl(r){return Fe(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(Ce(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function fy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+pe(t)}}function bl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function fd(r){return new Error("Error parsing address: "+r)}var hy=Symbol.for("nodejs.util.inspect.custom"),Al=Symbol.for("@multiformats/js-multiaddr/multiaddr"),dy=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],El=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},si=class r{bytes;#e;#t;#s;#a;[Al]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=xl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=ld(e)}else if(tr(e))t=xl(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=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),dy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=X(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=X(h).name,n=`${p??""}${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({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(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(vl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===ln.p2p.code&&e.push([n,o]),n===ln["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(ge.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ce(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=un.get(t.name);if(n==null)throw new El(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>se(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)}[hy](){return`Multiaddr(${this.#e})`}};var un=new Map;function tr(r){return!!r?.[Al]}function se(r){return new si(r)}var py=r=>r.toString().split("/").slice(1),ao=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),G=r=>({match:e=>ao(t=>t===r).match(e),pattern:r}),ci=()=>({match:r=>ao(e=>typeof e=="string").match(r),pattern:"{string}"}),li=()=>({match:r=>ao(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ie=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ii=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Cc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),ze=(...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(", ")})`}),Z=(...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 he(...r){function e(o){let s=py(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 ui=Z(G("dns4"),ci()),fi=Z(G("dns6"),ci()),hi=Z(G("dnsaddr"),ci()),_l=Z(G("dns"),ci()),RA=he(ui,te(ie())),DA=he(fi,te(ie())),MA=he(hi,te(ie())),UA=he(ze(_l,hi,ui,fi),te(ie())),hd=Z(G("ip4"),ao(an)),dd=Z(G("ip6"),ao(cn)),Bl=ze(hd,dd),Mt=ze(Bl,_l,ui,fi,hi),OA=he(ze(Bl,Z(ze(_l,hi,ui,fi),te(ie())))),FA=he(hd),VA=he(dd),HA=he(Bl),Il=Z(Mt,G("tcp"),li()),co=Z(Mt,G("udp"),li()),$A=he(Z(Il,te(ie()))),KA=he(co),kl=Z(co,G("quic")),di=Z(co,G("quic-v1")),my=ze(kl,di),qA=he(kl),zA=he(di),Sl=ze(Mt,Il,co,kl,di),pd=ze(Z(Sl,G("ws"),te(ie()))),GA=he(pd),md=ze(Z(Sl,G("wss"),te(ie())),Z(Sl,G("tls"),G("ws"),te(ie()))),WA=he(md),gd=Z(co,G("webrtc-direct"),te(ii()),te(ii()),te(ie())),jA=he(gd),yd=Z(di,G("webtransport"),te(ii()),te(ii()),te(ie())),ZA=he(yd),ai=ze(pd,md,Z(Il,te(ie())),Z(my,te(ie())),Z(Mt,te(ie())),gd,yd,ie()),XA=he(ai),gy=Z(ai,G("p2p-circuit"),ie()),lo=he(gy),yy=ze(Z(ai,G("p2p-circuit"),G("webrtc"),te(ie())),Z(ai,G("webrtc"),te(ie())),G("webrtc")),YA=he(yy),wy=ze(Z(Mt,G("tcp"),li(),G("http"),te(ie())),Z(Mt,G("http"),te(ie()))),JA=he(wy),by=ze(Z(Mt,G("tcp"),ze(Z(G("443"),G("http")),Z(li(),G("https"))),te(ie())),Z(Mt,G("tls"),G("http"),te(ie())),Z(Mt,G("https"),te(ie()))),QA=he(by);var bd=ar(wd(),1),xy=["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"],vy=xy.map(r=>new bd.Netmask(r));function Cl(r){for(let e of vy)if(e.contains(r))return!0;return!1}function Ey(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ay(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Cl(o)}function Sy(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function _y(r){let e=r.split(":"),t=e[e.length-1];return Cl(t)}function By(r){return/^::$/.test(r)||/^::1$/.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)}function pi(r){return an(r)?Cl(r):Ey(r)?Ay(r):Sy(r)?_y(r):cn(r)?By(r):void 0}function Tl(r){try{let{address:e}=r.nodeAddress();return!!pi(e)}catch{return!0}}function Iy(r,e){let t=Tl(r.multiaddr),n=Tl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function ky(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Cy(r,e){let t=lo.exactMatch(r.multiaddr),n=lo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function fn(r,e){let t=Iy(r,e);if(t!==0)return t;let n=Cy(r,e);return n!==0?n:ky(r,e)}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Nl=ar(vd(),1);var ho=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Pl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ed=r=>globalThis.DOMException===void 0?new Pl(r):new DOMException(r),Ad=r=>{let e=r.reason===void 0?Ed("This operation was aborted."):r.reason;return e instanceof Error?e:Ed(e)};function po(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:d}=e;d.aborted&&f(Ad(d)),d.addEventListener("abort",()=>{f(Ad(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new ho;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}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(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Rl(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 mo=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=Rl(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 rr=class extends Nl.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:mo,...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#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){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.#E()},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.#x){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#S(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=po(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof ho&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},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}};function gi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Dl=60;function yi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??Dl,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var Ny=4;function Ml(r,e={}){let t=new rr({concurrency:e.queryConcurrency??Ny});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),gi(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new de("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=yi(await a.json());return o.onProgress?.(new de("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Sd(){return[Ml("https://cloudflare-dns.com/dns-query"),Ml("https://dns.google/resolve")]}var Id=ar(Bd(),1);var Ul=class{lru;constructor(e){this.lru=(0,Id.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return yi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Dl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function kd(r){return new Ul(r)}var Py=1e3,wi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=kd(e.cacheSize??Py),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Sd())}async query(e,t={}){let n=gi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new de("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function Cd(r={}){return new wi(r)}var Ry=32,{code:Dy}=X("dnsaddr"),Ol=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},br=async function(e,t={}){let n=t.maxRecursiveDepth??Ry;if(n===0)throw new Ol("Max recursive depth reached");let[,o]=e.stringTuples().find(([u])=>u===Dy)??[],i=await(t?.dns??Cd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Od=ar(Ud(),1),vi=Od.default;var Hy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:br},addressSorter:fn},transportManager:{faultTolerance:Ft.FATAL_ALL}};async function Fd(r){let e=vi(Hy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function $y(r,e){try{if(typeof r=="string"&&r.length>0)return Ky(r);if(typeof r=="number"&&isFinite(r))return e?.long?zy(r):qy(r);throw new Error("Value is not a string or number.")}catch(t){let n=Gy(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ky(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let 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)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ai=$y;function qy(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function zy(r){let e=Math.abs(r);return e>=864e5?Ei(r,e,864e5,"day"):e>=36e5?Ei(r,e,36e5,"hour"):e>=6e4?Ei(r,e,6e4,"minute"):e>=1e3?Ei(r,e,1e3,"second"):`${r} ms`}function Ei(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Gy(r){return typeof r=="object"&&r!==null&&"message"in r}function Vl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Ai,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 d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=t.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(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,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;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.setupFormatters(t.formatters),t.enable(t.load()),t}var Si=Qy(),Wy=["#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 jy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Zy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ai(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)}var Xy=console.debug??console.log??(()=>{});function Yy(r){try{r?Si?.setItem("debug",r):Si?.removeItem("debug")}catch{}}function Jy(){let r;try{r=Si?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Qy(){try{return localStorage}catch{}}function ew(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Vd=Vl({formatArgs:Zy,save:Yy,load:Jy,useColors:jy,setupFormatters:ew,colors:Wy,storage:Si,log:Xy});var Ge=Vd;Ge.formatters.b=r=>r==null?"undefined":W.baseEncode(r);Ge.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ge.formatters.m=r=>r==null?"undefined":kc.baseEncode(r);Ge.formatters.p=r=>r==null?"undefined":r.toString();Ge.formatters.c=r=>r==null?"undefined":r.toString();Ge.formatters.k=r=>r==null?"undefined":r.toString();Ge.formatters.a=r=>r==null?"undefined":r.toString();Ge.formatters.e=r=>r==null?"undefined":r.stack??r.message;function tw(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 _i(){return{forComponent(r){return rw(r)}}}function rw(r){let e=tw(`${r}:trace`);return Ge.enabled(`${r}:trace`)&&Ge.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Ge(`${r}:trace`)),Object.assign(Ge(r),{error:Ge(`${r}:error`),trace:e})}function xr(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}function Bi(r){let e=rt(W.decode(`z${r}`));return on(e)}var lt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return xr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return xr(this.map.values(),e=>e.key)}values(){return xr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var vr=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 xr(this.set.entries(),e=>{let t=Bi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Bi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return xr(this.set.values(),e=>Bi(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 zd=Symbol.for("@achingbrain/uint8arraylist");function qd(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 ki(r){return!!r?.[zd]}var be=class r{bufs;length;[zd]=!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(ki(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(ki(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=qd(this.bufs,e);return t.buf[t.index]}set(e,t){let n=qd(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(ki(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 Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(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(!ki(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 d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-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=Ie(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=ue(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=ue(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=ue(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=Ie(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=ue(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=ue(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=ue(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=ue(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=ue(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(!ce(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 Hl=64,ut=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Hl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Er(r,e){return Math.floor(Math.random()*(e-r))+r}var Ar=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");let t=Er(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ut))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var $l={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Gd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Wd=new globalThis.TextEncoder;function nw(r,e){let t=$l[e],n=Gd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ow(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=$l[e],o=Gd[e],s=r;for(;s.length>0;){let i=Wd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Kl(r,{size:e=32,utf8Buffer:t}={}){if(!$l[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return ow(r,e,t);r=Wd.encode(r)}return nw(r,e)}var sw=ar(Kd(),1);var yo={hash:r=>Number(Kl(r,{size:32})),hashV:(r,e)=>iw(yo.hash(r,e))};function iw(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var aw=500,wo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??yo,this.seed=e.seed??Er(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ar(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ar(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Er(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ar(this.bucketSize));for(let a=0;a<aw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ar(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new ut(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},cw={1:.5,2:.84,4:.95,8:.98};function lw(r=.001){return r>.002?2:r>1e-5?4:8}function jd(r,e=.001){let t=lw(e),n=cw[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Hl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Ci=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??yo,this.seed=e.seed??Er(0,Math.pow(2,10)),this.filterSeries=[new wo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new wo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ql(r,e=.001,t){return new Ci({...jd(r,e),...t??{}})}var bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((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,o={})=>{let s={publicKey:ue(0),payloadType:ue(0),payload:ue(0),signature:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(bo||(bo={}));var Ti=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var pn=class r{static createFromProtobuf=async e=>{let t=bo.decode(e),n=nn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Zd(n,o,s),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ti("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=bo.encode({publicKey:ht(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ce(this.marshal(),e.marshal())}async validate(e){let t=Zd(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Zd=(r,e,t)=>{let n=P(r),o=Ce(n.byteLength),s=Ce(e.length),i=Ce(t.length);return new be(o,n,s,e,i,t)};function Xd(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 Yd="libp2p-peer-record",Jd=Uint8Array.from([3,1]);var xo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ue((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,a={})=>{let c={multiaddr:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Me(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((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,s={})=>{let i={peerId:ue(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(xo||(xo={}));var Sr=class r{static createFromProtobuf=e=>{let t=xo.decode(e),n=on(rt(t.peerId)),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Yd;static CODEC=Jd;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=xo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Xd(this.multiaddrs,e.multiaddrs))}};function uw(r){return r[Symbol.asyncIterator]!=null}function fw(r){if(uw(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 vo=fw;var nr={},mn=r=>{r.addEventListener("message",e=>{mn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{mn.dispatchEvent("message",r,e)})};mn.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};mn.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};mn.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var zl=mn;var Gl="lock:worker:request-read",Wl="lock:worker:release-read",jl="lock:master:grant-read",Zl="lock:worker:request-write",Xl="lock:worker:release-write",Yl="lock:master:grant-write";var Qd=(r=21)=>Math.random().toString().substring(2);var ep=(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)})}}}))},tp=(r,e,t,n)=>async()=>{let o=Qd();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)})},hw={singleProcess:!1},rp=r=>{if(r=Object.assign({},hw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return zl.addEventListener("message",ep(t,"requestReadLock",Gl,Wl,jl)),zl.addEventListener("message",ep(t,"requestWriteLock",Zl,Xl,Yl)),t}return{isWorker:!0,readLock:t=>tp(t,Gl,jl,Wl),writeLock:t=>tp(t,Zl,Yl,Xl)}};var _r={},or;async function Jl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>po((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var dw=(r,e)=>{if(or.isWorker===!0)return{readLock:or.readLock(r,e),writeLock:or.writeLock(r,e)};let t=new rr({concurrency:1}),n;return{async readLock(){if(n!=null)return Jl(n,e);n=new rr({concurrency:e.concurrency,autoStart:!1});let o=n,s=Jl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Jl(t,e)}}},pw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Ql(r){let e=Object.assign({},pw,r);return or==null&&(or=rp(e),or.isWorker!==!0&&(or.addEventListener("requestReadLock",t=>{_r[t.data.name]!=null&&_r[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),or.addEventListener("requestWriteLock",async t=>{_r[t.data.name]!=null&&_r[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),_r[e.name]==null&&(_r[e.name]=dw(e.name,e)),_r[e.name]}var gn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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,c={})=>{let u={key:"",value:ue(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((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),Ni.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=Ni.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Li.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,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new yr('Decode error - map field "addresses" had too many elements');a.addresses.push(Li.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new yr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new $n('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new $n('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Me(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(gn||(gn={}));var Li;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((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,o={})=>{let s={multiaddr:ue(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Li||(Li={}));var Ni;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((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,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ni||(Ni={}));function yn(r,e){let t=gn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=nn(t.publicKey);r=cl(s)}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 Ut="/",np=new TextEncoder().encode(Ut),Pi=np[0],Br=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(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]!==Pi)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}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=np),this._buf[0]!==Pi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Pi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Pi;)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(Ut).slice(1)}type(){return mw(this.baseNamespace())}name(){return gw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?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(),...yw(e.map(t=>t.namespaces()))])}};function mw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function gw(r){let e=r.split(":");return e[e.length-1]}function yw(r){return[].concat(...r)}var eu="/peers/";function wn(r){if(!Po(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Br(`${eu}${e}`)}async function op(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)),!tr(o.multiaddr))throw new D("Multiaddr was invalid");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 Di(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");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(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ri(d,{validate:sp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ri(d,{validate:ip,map:ap})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ri([...a.entries()],{validate:sp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ri([...h.entries()],{validate:ip,map:ap})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=ht(o.id.publicKey):e.publicKey!=null?f=ht(e.publicKey):r.publicKey!=null&&(f=ht(r.publicKey));let l={addresses:await op(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ri(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 sp(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function ip(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function ap(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 Mi(r,e,t){let n=r.toString().split("/")[2],o=ge.parse(n,We),s=ti(o),i=t.get(s);if(i!=null)return i;let a=yn(s,e);return t.set(s,a),a}function ww(r,e){return r==null?{}:{prefix:eu,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Mi(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Mi(n.key,n.value,e),Mi(o.key,o.value,e)))}}var Ui=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ql({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(wn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(wn(e))}async load(e){let t=await this.datastore.get(wn(e));return yn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Di(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 Di(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 Di(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new lt;for await(let{key:n,value:o}of this.datastore.query(ww(e??{},t))){let s=Mi(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(wn(e)),n=yn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let s=gn.encode(t);return n!=null&&ce(s,n)?{peer:yn(e,s),previous:o,updated:!1}:(await this.datastore.put(wn(e),s),{peer:yn(e,s),previous:o,updated:!0})}};var tu=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 Ui(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";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 vo(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 pn.openAndCertify(e,Sr.DOMAIN),o=ti(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let s=Sr.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await pn.createFromProtobuf(i.peerRecordEnvelope),c=Sr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 cp(r,e={}){return new tu(r,e)}var Oi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function bw(r){return r[Symbol.asyncIterator]!=null}function xw(r){if(bw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ru=xw;function vw(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 lp=vw;function Ew(r){return r[Symbol.asyncIterator]!=null}function Aw(r,e){let t=0;if(Ew(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=lp(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Ir=Aw;function Sw(r){return r[Symbol.asyncIterator]!=null}function _w(r,e){return Sw(r)?async function*(){yield*(await vo(r)).sort(e)}():function*(){yield*vo(r).sort(e)}()}var nu=_w;function Bw(r){return r[Symbol.asyncIterator]!=null}function Iw(r,e){return Bw(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 ou=Iw;var Fi=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 ru(this.putMany(e,n)),e=[],await ru(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=Ir(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>nu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Ir(n,()=>o++>=s)}return e.limit!=null&&(n=ou(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Ir(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Ir(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>nu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Ir(n,()=>s++>=o)}return e.limit!=null&&(n=ou(n,e.limit)),n}};var Vi=class extends Fi{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 new Oi;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 Br(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Br(e)}};function up(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var kw=r=>r;function su(r,e){let t=r.getPeerId();return t!=null&&yt(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var Hi=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??kw,this._updatePeerStoreAddresses=up(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_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=su(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=su(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=su(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 fp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(fp||(fp={}));var $i=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ki=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Eo=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ao=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},qi=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},zi=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Gi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},So=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},kr=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Wi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ji=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Cr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Tr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Zi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var iu=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=_i())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ko(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")}},Tw=["metrics","connectionProtector","dns"],Lw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function hp(r={}){let e=new iu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Lw.includes(o)){let i=e.components[o];if(i==null&&!Tw.includes(o))throw new $i(`${o} not set`);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}})}function dp(r){let e={};for(let t of Object.values(r.components))for(let n of Nw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Pw(t))if(e[n]!==!0)throw new Ki(`Service "${Rw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Nw(r){return Array.isArray(r?.[kn])?r[kn]:[]}function Pw(r){return Array.isArray(r?.[Oa])?r[Oa]:[]}function Rw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function pp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!pi(`${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 mp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Dw=new WeakMap;function Mw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(mp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(mp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Dw.set(l,()=>{c(s),s=null,i()}),l}}var Uw=Mw(),gp=Uw;var Xi=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var Yi=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 au}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 Xi("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 gp(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)}},au=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 Ji(r){if(Po(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:yt(t),r.forEach(n=>{if(!tr(n))throw new Vt("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=yt(o);if(e?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Ow=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function yp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Ow;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var wp="last-dial-failure",bp="last-dial-success";var Qi=100,ea=50;var xp={maxConnections:Qi,allow:[]},ta=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??xp.maxConnections,this.allow=t.allow??xp.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;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new lt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];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()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await yp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ra=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}},bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ra(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 ra(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 cu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function na(r={}){return Fw(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 Fw(r,e){e=e??{};let t=e.onEnd,n=new bn,o,s,i,a=fe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new bn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.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=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new bn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new cu)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var lu=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 xn(r,e,t,n){let o=new lu(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var oa=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function sr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new oa(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new oa(t?.errorMessage,t?.errorCode,t?.errorName);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 sa=class{deferred;signal;constructor(e){this.signal=e,this.deferred=fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new et)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Vw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ia=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Vw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ee(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 et),this.cleanup())}async join(e={}){let t=new sa(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 sr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var vn=class extends xt{concurrency;queue;pending;sort;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.sort=e.sort,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){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new ia(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new et)}),this.clear()}async onEmpty(e){this.size!==0&&await xn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await xn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await xn(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=na({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 et("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 aa=class extends vn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ot(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 vp(r,e){let t=!1;for(let o of un.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var _o={addressSorter:fn,maxParallelDials:ea,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:br}},ca=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??_o.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??_o.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??_o.maxDialQueueLength,this.dialTimeout=t.dialTimeout??_o.dialTimeout,this.connections=t.connections??new lt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))un.set(n,o);this.queue=new aa({concurrency:t.maxParallelDials??_o.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==et.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,ee(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ji(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),t.onProgress?.(new de("dial-queue:already-connected")),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 t.onProgress?.(new de("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Dr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new de("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new de("dial-queue:calculated-addresses",u)),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 d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Dr("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[bp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[wp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Vo(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??du,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Ot([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ee(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 Dr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new So("The dial request is blocked by gater.allowDialPeer");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:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")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:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&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 d=await vp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new kr("The dial request has 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 So("The connection gater denied all addresses in the dial request");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}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!lo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var la=class extends vn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var kp=ar(Bp(),1);var $w=Object.prototype.toString,Kw=r=>$w.call(r)==="[object Error]",qw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function pu(r){return r&&Kw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:qw.has(r.message):!1}var mu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Ip=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function gu(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=kp.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof mu)throw c.originalError;if(c instanceof TypeError&&!pu(c))throw c;if(Ip(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Ip(u,a,e),i(),n(u)}}})})}var ua=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new la({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(e){!this.started||!(await this.peerStore.get(e)).tags.has(Ua)||this.queue.has(e)||this.queue.add(async n=>{await gu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(n=>{this.log.error("failed to reconnect to %p",e,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Ua)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};var du=50,yu={maxConnections:Qi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},fa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??yu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new lt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(n=>se(n)),this.deny=(t.deny??[]).map(n=>se(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??yu.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Yi({points:t.inboundConnectionThreshold??yu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ta({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ca(e,{addressSorter:t.addressSorter??fn,maxParallelDials:t.maxParallelDials??ea,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:br},connections:this.connections}),this.reconnectQueue=new ua({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,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}}),await Ou(this.dialQueue,this.reconnectQueue),this.started=!0,this.log("started")}async stop(){await Fu(this.reconnectQueue,this.dialQueue);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 bt("Not started");t.signal?.throwIfAborted();let{peerId:n}=Ji(e);if(this.peerId.equals(n))throw new Bn("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new de("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??du});if(o.remotePeer.equals(this.peerId)){let a=new Bn("Can not dial self");throw o.abort(a),a}let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Vt("Duplicate multiaddr connection")),a;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))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var En=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Ww=1.2,jw=2,Zw=2e3,ha=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new En(e.interval??5e3),this.failure=new En(e.interval??5e3),this.next=new En(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??jw,this.timeoutMultiplier=e.timeoutMultiplier??Ww,this.minTimeout=e.minTimeout??Zw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Ot([e.signal,n]);return ee(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var wu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=fe(),this.haveNext=fe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=fe(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),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");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=fe(),await sr(this.readNext.promise,t?.signal,t)}};function Cp(){return new wu}var da=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var bu=class extends Error{code;constructor(e,t){super(e),this.code=t}},xu=class extends bu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function pa(r,e){let t=Cp();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 be;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new xu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new be:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new da("unexpected end of input");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}}}var Xw=1e4,Yw="1.0.0",Jw="ping",Qw="ipfs",Tp=32,eb=!0,ma=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Qw}/${Jw}/${Yw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Xw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??eb,this.timeout=new ha({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[kn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,ee(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=pa(o);t=Date.now(),await Promise.all([s.write(tn(Tp),{signal:n}),s.read(Tp,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function tb(r){return r[Symbol.asyncIterator]!=null}function rb(...r){let e=[];for(let t of r)tb(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=na({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 Bo=rb;var ga=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Eo("No content routers available");let n=this,o=new vr;for await(let s of Bo(...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 Eo("No content 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 bt;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new bt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ya=globalThis.CustomEvent??Event;async function*vu(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=fe(),a=fe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=fe(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new ya("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ya("task-complete"))})}c=!0,o.dispatchEvent(new ya("task-complete"))}catch(p){u=p,o.dispatchEvent(new ya("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=fe(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var wa=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??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ao("No peer routers available");if(e.toString()===this.peerId.toString())throw new qi("Should not try to find self");let n=this,o=Bo(...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 Mo}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ao("No peer routers available");let n=this,o=ql(1024);for await(let s of vu(async function*(){let i=Bo(...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.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ba=class extends xt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ee(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ee(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ot([this.shutdownController.signal,e?.signal]);ee(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=fe(),yield(await xn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ee(1/0,this.walkController.signal);let e=Ot([this.walkController.signal,this.shutdownController.signal]);ee(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await sr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Eu=32,Au=64,xa=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new zi(`No handler registered for protocol ${e}`);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 Gi(`Handler already registered for protocol ${e}`);let o=vi.bind({ignoreUndefined:!0})({maxInboundStreams:Eu,maxOutboundStreams:Au},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 D("invalid topology");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.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&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.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),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.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Su=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 Lp(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Su({name:e,metrics:t}):n=new Map,n}var va=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=Lp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){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.dialTransportForMultiaddr(e);if(n==null)throw new Zi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}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()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new bt("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.listenFilter(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 d=l.findIndex(h=>h===f);l.splice(d,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!==Ft.NO_FATAL)throw new kr(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ft.FATAL_ALL)throw new kr(n);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 Be="/multistream/1.0.0";var Ea=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Aa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Sa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,e={}){let t=pa(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??Ce;return{read:async i=>{let a=-1,c=new be;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Ea("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Sa("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Aa("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new be(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new be(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var nb=P(`
7
+ `);async function Nr(r,e,t){await r.write(e,t)}async function Np(r,e,t){await r.writeV(e,t)}async function ob(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==nb[0])throw e.log.error("Invalid mss message - missing newline",t),new Fo("Missing newline");return t.sublist(0,-1)}async function ir(r,e){let t=await ob(r,e);return H(t.subarray())}async function ko(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return sb(r,e[0],t);let n=Io(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Be,o);let s=P(`${Be}
8
8
  `),i=P(`${o}
9
- `);await Lp(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await sr(n,e);if(e.log.trace('select: read "%s"',a),a===Bt&&(e.log.trace("select: reading protocol response"),a=await sr(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Tr(n,P(`${c}
10
- `),e),e.log.trace("select: reading protocol response");let u=await sr(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new _n("protocol selection failed")}function ob(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=lt(),c=!1,u=!1,f=lt(),l=!1,d=!1,h=lt(),p=Bo({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let x=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Bt,t,A.byteLength);let _=`${t}
11
- `;yield new wt(Uint8Array.from([19]),P(`${Bt}
12
- `),Ct(_.length),P(_),A).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Bt,t,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,v)})}x=!0}x||await m()}())};async function m(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await g()),l||(e.log.trace("optimistic: doing read protocol for %s stream",t),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',Bt,t),await p.writeV([P(`${Bt}
13
- `),P(`${t}
14
- `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',Bt,t)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let b=await sr(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',b),b===Bt&&(b=await sr(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',b,t),b!==t)throw new _n("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(x=>{e.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(x=>{e.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await or(Promise.all(x),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:t}}function va(r){return r[Symbol.asyncIterator]!=null}var Ea=r=>{let t=ht(r),e=It(t);return Ct(r,e),Ea.bytes=t,e};Ea.bytes=0;function Aa(r,t){t=t??{};let e=t.lengthEncoder??Ea;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return va(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Aa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ea;return new wt(e(r.byteLength),r)};var Sa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_a=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ba=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ko=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var sb=8,ib=1024*1024*4,Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Su=r=>{let t=se(r);return Su.bytes=ht(t),t};Su.bytes=0;function Au(r,t){let e=new wt,n=Lr.LENGTH,o=-1,s=t?.lengthDecoder??Su,i=t?.maxLengthLength??sb,a=t?.maxDataLength??ib;function*c(){for(;e.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(e),o<0)throw new Sa("Invalid message length");if(o>a)throw new _a("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Lr.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new Ba("Message length length too long");break}throw u}if(n===Lr.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Lr.LENGTH}}}return va(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new ko("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new ko("Unexpected end of input")}()}Au.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Au(n,{...t??{},onLength:s=>{e=s}})};async function Co(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Bo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await sr(n,e);if(e.log.trace('handle: read "%s"',o),o===Bt){e.log.trace('handle: respond with "%s" for "%s"',Bt,o),await Tr(n,P(`${Bt}
15
- `),e),e.log.trace('handle: responded with "%s" for "%s"',Bt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Tr(n,P(`${o}
16
- `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new wt(...t.map(i=>Aa.single(P(`${i}
9
+ `);await Np(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await ir(n,t);if(t.log.trace('select: read "%s"',a),a===Be&&(t.log.trace("select: reading protocol response"),a=await ir(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Nr(n,P(`${c}
10
+ `),t),t.log.trace("select: reading protocol response");let u=await ir(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new In("protocol selection failed")}function sb(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=fe(),c=!1,u=!1,f=fe(),l=!1,d=!1,h=fe(),p=Io({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let x=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength);let _=`${e}
11
+ `;yield new be(Uint8Array.from([19]),P(`${Be}
12
+ `),Ce(_.length),P(_),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,v)})}x=!0}x||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Be,e),await p.writeV([P(`${Be}
13
+ `),P(`${e}
14
+ `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Be,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await ir(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===Be&&(b=await ir(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new In("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await sr(Promise.all(x),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:e}}function _a(r){return r[Symbol.asyncIterator]!=null}var Ba=r=>{let e=pe(r),t=Ie(e);return Ce(r,t),Ba.bytes=e,t};Ba.bytes=0;function Ia(r,e){e=e??{};let t=e.lengthEncoder??Ba;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return _a(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Ia.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ba;return new be(t(r.byteLength),r)};var ka=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ca=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ta=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Co=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ib=8,ab=1024*1024*4,Pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Pr||(Pr={}));var Iu=r=>{let e=it(r);return Iu.bytes=pe(e),e};Iu.bytes=0;function Bu(r,e){let t=new be,n=Pr.LENGTH,o=-1,s=e?.lengthDecoder??Iu,i=e?.maxLengthLength??ib,a=e?.maxDataLength??ab;function*c(){for(;t.byteLength>0;){if(n===Pr.LENGTH)try{if(o=s(t),o<0)throw new ka("Invalid message length");if(o>a)throw new Ca("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Pr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ta("Message length length too long");break}throw u}if(n===Pr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Pr.LENGTH}}}return _a(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Co("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Co("Unexpected end of input")}()}Bu.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 Bu(n,{...e??{},onLength:s=>{t=s}})};async function To(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Io(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await ir(n,t);if(t.log.trace('handle: read "%s"',o),o===Be){t.log.trace('handle: respond with "%s" for "%s"',Be,o),await Nr(n,P(`${Be}
15
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',Be,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Nr(n,P(`${o}
16
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new be(...e.map(i=>Ia.single(P(`${i}
17
17
  `))),P(`
18
- `));e.log.trace('handle: respond with "%s" for %s',t,o),await Tr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log('handle: respond with "na" for "%s"',o),await Tr(n,P(`na
19
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var cb=500,_u=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,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=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ru]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Po("the connection is being closed");if(this.status==="closed")throw new Ro("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Dr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);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 e=AbortSignal.timeout(cb);tt(1/0,e),t={...t,signal:e}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async e=>e.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(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(e=>{e.abort(t)}),this.log.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}};function Pp(r){return new _u(r)}function fb(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return bu}function hb(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??xu}function Rp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ia=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=e.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??2e3,this.events=t.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Ki(`The multiaddr connection is blocked by gater.${t}`)}async upgradeInbound(t,e={}){try{if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new qi("connection denied");return await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",e)}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e={}){let n=t.remoteAddr.getPeerId(),o;return n!=null&&(o=ge(n),await this.shouldBlockConnection("denyOutboundConnection",o,t)),this._performUpgrade(t,"outbound",e)}async _performUpgrade(t,e,n){let o,s,i,a,c,u=AbortSignal.timeout(e==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Oe([u,n.signal]);tt(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),l=await d.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new ft(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(e==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Pr(`${e} connection that skipped encryption must have a peer id`);let h=ge(d);c="native",s=h}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new ft(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully %s inbound connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);tt(1/0,g);let{stream:y,protocol:b}=await Co(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let w=fb(b,this.components.registrar);if(Rp(b,"inbound",l)===w){let A=new Vo(`Too many inbound protocol streams for protocol "${b}" - limit ${w}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=b,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[b]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:b})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new kr("Connection is not multiplexed");l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);tt(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await Io(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=hb(b,this.components.registrar,m),x=Rp(b,"outbound",l);if(x>=w){let A=new Ho(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,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,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new kr("Connection is not multiplexed")};return l=Pp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Dr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await Co(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting inbound connection using",s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection failed",o),new Ao(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("selecting outbound crypto protocol",n);try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Io(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %p using %s",e?.remotePeer,i),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %p failed",e?.remotePeer,o),new Ao(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Io(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new kr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Co(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new kr(String(s))}}};var Dp="2.1.2",Mp="libp2p";var ka=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},tt(1/0,e),this.peerId=t.peerId,this.logger=t.logger??vi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=fp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:Mp,version:Dp},logger:this.logger,events:e,datastore:t.datastore??new Mi,connectionGater:dp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",ap(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.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})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new Ia(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:t.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new ya(this.components,t.transportManager)),this.configureComponent("connectionManager",new aa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new fa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new ga(this.components)),this.configureComponent("addressManager",new Ui(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new pa(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ha(this.components,{routers:i})),this.configureComponent("randomWalk",new ma(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),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[Ta]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ta])),u[Na]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Na])),u[La]!=null&&(this.log("registering service %s for peer discovery",a),u[La].addEventListener?.("peer",f=>{this.#t(f)}))}hp(o)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}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 xr;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new D("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){tr(t)&&(t=ge(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ft([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=rn(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function pb(r={}){r.privateKey??=await Wh("Ed25519");let t=new ka({...await Od(r),peerId:Yh(r.privateKey)});return r.start!==!1&&await t.start(),t}return Xp(mb);})();
18
+ `));t.log.trace('handle: respond with "%s" for %s',e,o),await Nr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log.trace('handle: respond with "na" for "%s"',o),await Nr(n,P(`na
19
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var lb=500,ku=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;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.limits=e.limits,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";[Uu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Ro("the connection is being closed");if(this.status==="closed")throw new Do("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited 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(lb);ee(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 Rp(r){return new ku(r)}function hb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Eu}function db(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Au}function Dp(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var La=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Wi(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){try{if(this.metrics.dials?.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(e))throw new ji("connection denied");return await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(n){throw this.metrics.errors?.increment({inbound:!0}),n}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;return n!=null&&(o=yt(n),await this.shouldBlockConnection("denyOutboundConnection",o,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,s,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ot([u,n.signal]);ee(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),l=await d.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new de(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let h=yt(d);c="native",s=h}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);ee(1/0,g);let{stream:y,protocol:b}=await To(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let w=hb(b,this.components.registrar);if(Dp(b,"inbound",l)===w){let A=new Ho(`Too many inbound protocol streams for protocol "${b}" - limit ${w}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=b,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[b]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:b})}).catch(async m=>{l.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new Cr("Connection is not multiplexed");l.log.trace("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);ee(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await ko(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",b);let w=db(b,this.components.registrar,m),x=Dp(b,"outbound",l);if(x>=w){let A=new $o(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,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,l),g}catch(y){throw l.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new Cr("Connection is not multiplexed")};return l=Rp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),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.limits!=null&&i.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await To(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new Tr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await ko(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Tr(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new Tr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await ko(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing outbound connection",s),new Cr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await To(e,o,{...n,log:e.log}),a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing inbound connection",s),new Cr(String(s))}}};var Mp="2.1.3-a390db4a4",Up="libp2p";var Na=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},ee(1/0,t),this.peerId=e.peerId,this.logger=e.logger??_i(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=hp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Up,version:Mp},logger:this.logger,events:t,datastore:e.datastore??new Vi,connectionGater:pp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",cp(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 La(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new va(this.components,e.transportManager)),this.configureComponent("connectionManager",new fa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ma(this.components,e.connectionMonitor)),this.configureComponent("registrar",new xa(this.components)),this.configureComponent("addressManager",new Hi(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 wa(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 ga(this.components,{routers:i})),this.configureComponent("randomWalk",new ba(this.components)),(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[Ra]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ra])),u[Ma]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ma])),u[Da]!=null&&(this.log("registering service %s for peer discovery",a),u[Da].addEventListener?.("peer",f=>{this.#e(f)}))}dp(o)}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 vr;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 D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a 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={}){tr(e)&&(e=yt(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 i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=nn(o);return await this.peerStore.patch(e,{publicKey:s}),s}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)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function mb(r={}){r.privateKey??=await Xh("Ed25519");let e=new Na({...await Fd(r),peerId:ed(r.privateKey)});return r.start!==!1&&await e.start(),e}return Yp(gb);})();
20
20
  /*! Bundled license information:
21
21
 
22
22
  pvtsutils/build/index.js: