libp2p 2.3.1-06f79b646 → 2.3.1-2625cc323
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 +13 -13
- package/dist/src/address-manager/dns-mappings.d.ts +20 -0
- package/dist/src/address-manager/dns-mappings.d.ts.map +1 -0
- package/dist/src/address-manager/dns-mappings.js +139 -0
- package/dist/src/address-manager/dns-mappings.js.map +1 -0
- package/dist/src/{address-manager.d.ts → address-manager/index.d.ts} +33 -8
- package/dist/src/address-manager/index.d.ts.map +1 -0
- package/dist/src/address-manager/index.js +264 -0
- package/dist/src/address-manager/index.js.map +1 -0
- package/dist/src/address-manager/ip-mappings.d.ts +18 -0
- package/dist/src/address-manager/ip-mappings.d.ts.map +1 -0
- package/dist/src/address-manager/ip-mappings.js +143 -0
- package/dist/src/address-manager/ip-mappings.js.map +1 -0
- package/dist/src/address-manager/observed-addresses.d.ts +19 -0
- package/dist/src/address-manager/observed-addresses.d.ts.map +1 -0
- package/dist/src/address-manager/observed-addresses.js +70 -0
- package/dist/src/address-manager/observed-addresses.js.map +1 -0
- package/dist/src/address-manager/transport-addresses.d.ts +19 -0
- package/dist/src/address-manager/transport-addresses.d.ts.map +1 -0
- package/dist/src/address-manager/transport-addresses.js +83 -0
- package/dist/src/address-manager/transport-addresses.js.map +1 -0
- package/dist/src/connection-manager/index.d.ts +1 -0
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +3 -0
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/libp2p.js +1 -1
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +10 -10
- package/src/address-manager/dns-mappings.ts +182 -0
- package/src/address-manager/index.ts +413 -0
- package/src/address-manager/ip-mappings.ts +191 -0
- package/src/address-manager/observed-addresses.ts +94 -0
- package/src/address-manager/transport-addresses.ts +116 -0
- package/src/connection-manager/index.ts +4 -0
- package/src/index.ts +1 -1
- package/src/libp2p.ts +1 -1
- package/src/version.ts +1 -1
- package/dist/src/address-manager.d.ts.map +0 -1
- package/dist/src/address-manager.js +0 -312
- package/dist/src/address-manager.js.map +0 -1
- package/src/address-manager.ts +0 -454
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 _m=Object.create;var Mo=Object.defineProperty;var Bm=Object.getOwnPropertyDescriptor;var Cm=Object.getOwnPropertyNames;var Im=Object.getPrototypeOf,km=Object.prototype.hasOwnProperty;var Qe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Re=(r,e)=>{for(var t in e)Mo(r,t,{get:e[t],enumerable:!0})},of=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Cm(e))!km.call(r,o)&&o!==t&&Mo(r,o,{get:()=>e[o],enumerable:!(n=Bm(e,o))||n.enumerable});return r};var hr=(r,e,t)=>(t=r!=null?_m(Im(r)):{},of(e||!r||!r.__esModule?Mo(t,"default",{value:r,enumerable:!0}):t,r)),Tm=r=>of(Mo({},"__esModule",{value:!0}),r);var mh=Qe(nn=>{"use strict";var ry="[object ArrayBuffer]",kt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===ry}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}},ll="string",ny=/^[0-9a-f\s]+$/i,oy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,sy=/^[a-zA-Z0-9-_]+$/,bs=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}},xs=class r{static isHex(e){return typeof e===ll&&ny.test(e)}static isBase64(e){return typeof e===ll&&oy.test(e)}static isBase64Url(e){return typeof e===ll&&sy.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 bs.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 bs.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,"")||""}};xs.DEFAULT_UTF8_ENCODING="utf8";function iy(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 ay(...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 cy(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}nn.BufferSourceConverter=kt;nn.Convert=xs;nn.assign=iy;nn.combine=ay;nn.isEqual=cy});var Nd=Qe((xA,Bl)=>{"use strict";var Ny=Object.prototype.hasOwnProperty,He="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(He=!1));function Py(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ld(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Py(t,n||r,o),i=He?He+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 di(r,e){--r._eventsCount===0?r._events=new ho:delete r._events[e]}function Ne(){this._events=new ho,this._eventsCount=0}Ne.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ny.call(t,n)&&e.push(He?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ne.prototype.listeners=function(e){var t=He?He+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=He?He+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=He?He+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 Ld(this,e,t,n,!1)};Ne.prototype.once=function(e,t,n){return Ld(this,e,t,n,!0)};Ne.prototype.removeListener=function(e,t,n,o){var s=He?He+e:e;if(!this._events[s])return this;if(!t)return di(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&di(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:di(this,s)}return this};Ne.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&di(this,t)):(this._events=new ho,this._eventsCount=0),this};Ne.prototype.off=Ne.prototype.removeListener;Ne.prototype.addListener=Ne.prototype.on;Ne.prefixed=He;Ne.EventEmitter=Ne;typeof Bl<"u"&&(Bl.exports=Ne)});var Ud=Qe((qA,Md)=>{Md.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 Qd=Qe((_8,Jd)=>{"use strict";Jd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var sp=Qe((np,op)=>{"use strict";var vi=Qd(),{hasOwnProperty:tp}=Object.prototype,{propertyIsEnumerable:ow}=Object,yn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),sw=np,ep={concatArrays:!1,ignoreUndefined:!1},Ei=r=>{let e=[];for(let t in r)tp.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)ow.call(r,n)&&e.push(n)}return e};function wn(r){return Array.isArray(r)?iw(r):vi(r)?aw(r):r}function iw(r){let e=r.slice(0,0);return Ei(r).forEach(t=>{yn(e,t,wn(r[t]))}),e}function aw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ei(r).forEach(t=>{yn(e,t,wn(r[t]))}),e}var rp=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?yn(r,o,Zl(r[o],e[o],n)):yn(r,o,wn(e[o])))}),r),cw=(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++)tp.call(s,a)&&(i.push(String(a)),s===r?yn(n,o++,s[a]):yn(n,o++,wn(s[a])));n=rp(n,s,Ei(s).filter(a=>!i.includes(a)),t)}),n};function Zl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?cw(r,e,t):!vi(e)||!vi(r)?wn(e):rp(r,e,Ei(e),t)}op.exports=function(...r){let e=Zl(wn(ep),this!==sw&&this||{},ep),t={_:{}};for(let n of r)if(n!==void 0){if(!vi(n))throw new TypeError("`"+n+"` is not an Option Object");t=Zl(t,{_:n},e)}return t._}});var up=Qe((yo,ki)=>{(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,w=p,b=0,y=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,y),b=s(b,15),b=o(b,x),w^=b,w=s(w,13),w=o(w,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,y),b=s(b,15),b=o(b,x),w^=b}return w^=h.length,w=i(w),w>>>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,w=p,b=p,y=p,x=p,A=0,_=0,v=0,B=0,k=597399067,Y=2869860233,H=951274213,V=2716044179,D=0;D<g;D=D+16)A=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,_=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,v=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,B=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,A=o(A,k),A=s(A,15),A=o(A,Y),w^=A,w=s(w,19),w+=b,w=o(w,5)+1444728091,_=o(_,Y),_=s(_,16),_=o(_,H),b^=_,b=s(b,17),b+=y,b=o(b,5)+197830471,v=o(v,H),v=s(v,17),v=o(v,V),y^=v,y=s(y,15),y+=x,y=o(y,5)+2530024501,B=o(B,V),B=s(B,18),B=o(B,k),x^=B,x=s(x,13),x+=w,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[D+14]<<16;case 14:B^=h[D+13]<<8;case 13:B^=h[D+12],B=o(B,V),B=s(B,18),B=o(B,k),x^=B;case 12:v^=h[D+11]<<24;case 11:v^=h[D+10]<<16;case 10:v^=h[D+9]<<8;case 9:v^=h[D+8],v=o(v,H),v=s(v,17),v=o(v,V),y^=v;case 8:_^=h[D+7]<<24;case 7:_^=h[D+6]<<16;case 6:_^=h[D+5]<<8;case 5:_^=h[D+4],_=o(_,Y),_=s(_,16),_=o(_,H),b^=_;case 4:A^=h[D+3]<<24;case 3:A^=h[D+2]<<16;case 2:A^=h[D+1]<<8;case 1:A^=h[D],A=o(A,k),A=s(A,15),A=o(A,Y),w^=A}return w^=h.length,b^=h.length,y^=h.length,x^=h.length,w+=b,w+=y,w+=x,b+=w,y+=w,x+=w,w=i(w),b=i(b),y=i(y),x=i(x),w+=b,w+=y,w+=x,b+=w,y+=w,x+=w,("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(y>>>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,w=[0,p],b=[0,p],y=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)y=[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],y=c(y,A),y=u(y,31),y=c(y,_),w=l(w,y),w=u(w,27),w=a(w,b),w=a(c(w,[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,w),b=a(c(b,[0,5]),[0,944331445]);switch(y=[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:y=l(y,f([0,h[v+7]],56));case 7:y=l(y,f([0,h[v+6]],48));case 6:y=l(y,f([0,h[v+5]],40));case 5:y=l(y,f([0,h[v+4]],32));case 4:y=l(y,f([0,h[v+3]],24));case 3:y=l(y,f([0,h[v+2]],16));case 2:y=l(y,f([0,h[v+1]],8));case 1:y=l(y,[0,h[v]]),y=c(y,A),y=u(y,31),y=c(y,_),w=l(w,y)}return w=l(w,[0,h.length]),b=l(b,[0,h.length]),w=a(w,b),b=a(b,w),w=d(w),b=d(b),w=a(w,b),b=a(b,w),("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof yo<"u"?(typeof ki<"u"&&ki.exports&&(yo=ki.exports=t),yo.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)})(yo)});var hp=Qe((Q8,fp)=>{fp.exports=up()});var Up=Qe(_o=>{(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}(),_o.ip2long=i,_o.long2ip=a,_o.Netmask=r}).call(_o)});var tm=Qe((p4,em)=>{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))}em.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 rm=Qe(Or=>{var Vb=tm();Or.operation=function(r){var e=Or.timeouts(r);return new Vb(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Or.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};Or.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};Or.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=Or.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 om=Qe((g4,nm)=>{nm.exports=rm()});var mx={};Re(mx,{createLibp2p:()=>px});var sf=Symbol.for("@libp2p/connection");var Ga=Symbol.for("@libp2p/content-routing");var Wa=Symbol.for("@libp2p/peer-discovery");var Uo=Symbol.for("@libp2p/peer-id");function Oo(r){return!!r?.[Uo]}var ja=Symbol.for("@libp2p/peer-routing");var Za="keep-alive";var Ax=Symbol.for("@libp2p/transport");var Ht;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var et=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Hr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Ln=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Fo=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Kr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Vo=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},qr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Kt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ho=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ko=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Nn=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},qo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var $o=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},xt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var $r=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var zr=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},zo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Go=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},qt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var oe=(r,...e)=>{try{[...e]}catch{}};var vt=class extends EventTarget{#e=new Map;constructor(){super(),oe(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 Wo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function af(...r){let e=[];for(let t of r)Wo(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 cf(...r){let e=[];for(let t of r)Wo(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 Pn=Symbol.for("@libp2p/service-capabilities"),Xa=Symbol.for("@libp2p/service-dependencies");var tc={};Re(tc,{base58btc:()=>Z,base58flickr:()=>Mm});var Qx=new Uint8Array(0);function lf(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 Et(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 uf(r){return new TextEncoder().encode(r)}function ff(r){return new TextDecoder().decode(r)}function Lm(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,w=0,b=p.length;w!==b&&p[w]===0;)w++,m++;for(var y=(b-w)*f+1>>>0,x=new Uint8Array(y);w!==b;){for(var A=p[w],_=0,v=y-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=_,w++}for(var B=y-g;B!==y&&x[B]===0;)B++;for(var k=c.repeat(m);B<y;++B)k+=r.charAt(x[B]);return k}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,w=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,y=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<w)&&_!==-1;_--,A++)x+=a*y[_]>>>0,y[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");w=A,m++}if(p[m]!==" "){for(var v=b-w;v!==b&&y[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),k=g;v!==b;)B[k++]=y[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 Nm=Lm,Pm=Nm,df=Pm;var Ya=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")}},Ja=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 pf(this,e)}},Qa=class{decoders;constructor(e){this.decoders=e}or(e){return pf(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 pf(r,e){return new Qa({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ec=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 Ya(e,t,n),this.decoder=new Ja(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gr({name:r,prefix:e,encode:t,decode:n}){return new ec(r,e,t,n)}function $t({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=df(t,r);return Gr({prefix:e,name:r,encode:n,decode:s=>Et(o(s))})}function Dm(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 le({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Gr({prefix:e,name:r,encode(o){return Rm(o,n,t)},decode(o){return Dm(o,n,t,r)}})}var Z=$t({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mm=$t({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var rc={};Re(rc,{base32:()=>We,base32hex:()=>Vm,base32hexpad:()=>Km,base32hexpadupper:()=>qm,base32hexupper:()=>Hm,base32pad:()=>Om,base32padupper:()=>Fm,base32upper:()=>Um,base32z:()=>$m});var We=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Um=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Om=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fm=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vm=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hm=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Km=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qm=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$m=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nc={};Re(nc,{base36:()=>Dn,base36upper:()=>zm});var Dn=$t({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zm=$t({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gm=yf,mf=128,Wm=127,jm=~Wm,Zm=Math.pow(2,31);function yf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zm;)e[t++]=r&255|mf,r/=128;for(;r&jm;)e[t++]=r&255|mf,r>>>=7;return e[t]=r|0,yf.bytes=t-n+1,e}var Xm=oc,Ym=128,gf=127;function oc(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw oc.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&gf)<<o:(i&gf)*Math.pow(2,o),o+=7}while(i>=Ym);return oc.bytes=s-n,t}var Jm=Math.pow(2,7),Qm=Math.pow(2,14),eg=Math.pow(2,21),tg=Math.pow(2,28),rg=Math.pow(2,35),ng=Math.pow(2,42),og=Math.pow(2,49),sg=Math.pow(2,56),ig=Math.pow(2,63),ag=function(r){return r<Jm?1:r<Qm?2:r<eg?3:r<tg?4:r<rg?5:r<ng?6:r<og?7:r<sg?8:r<ig?9:10},cg={encode:Gm,decode:Xm,encodingLength:ag},lg=cg,Rn=lg;function Mn(r,e=0){return[Rn.decode(r,e),Rn.decode.bytes]}function Wr(r,e,t=0){return Rn.encode(r,e,t),e}function jr(r){return Rn.encodingLength(r)}function tt(r,e){let t=e.byteLength,n=jr(r),o=n+jr(t),s=new Uint8Array(o+t);return Wr(r,s,0),Wr(t,s,n),s.set(e,o),new Zr(r,t,e,s)}function rt(r){let e=Et(r),[t,n]=Mn(e),[o,s]=Mn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Zr(t,o,i,e)}function wf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&lf(r.bytes,t.bytes)}}var Zr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function bf(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return fg(t,sc(r),e??Z.encoder);default:return hg(t,sc(r),e??We.encoder)}}var xf=new WeakMap;function sc(r){let e=xf.get(r);if(e==null){let t=new Map;return xf.set(r,t),t}return e}var me=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!==Un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dg)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&&wf(e.multihash,n.multihash)}toString(e){return bf(this,e)}toJSON(){return{"/":bf(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??vf(n,o,s.bytes))}else if(t[pg]===!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!==Un)throw new Error(`Version 0 CID must use dag-pb (code: ${Un}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=vf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Un,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=Et(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Zr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=Mn(e.subarray(t));return t+=d,l},o=n(),s=Un;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]=ug(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 sc(s).set(n,e),s}};function ug(r,e){switch(r[0]){case"Q":{let t=e??Z;return[Z.prefix,t.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let t=e??Z;return[Z.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Dn.prefix:{let t=e??Dn;return[Dn.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 fg(r,e,t){let{prefix:n}=t;if(n!==Z.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 hg(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 Un=112,dg=18;function vf(r,e,t){let n=jr(r),o=n+jr(e),s=new Uint8Array(o+t.byteLength);return Wr(r,s,0),Wr(e,s,n),s.set(t,o),s}var pg=Symbol.for("@ipld/js-cid/CID");var ic={};Re(ic,{identity:()=>St});var Ef=0,mg="identity",Af=Et;function gg(r){return tt(Ef,Af(r))}var St={code:Ef,name:mg,encode:Af,digest:gg};function ue(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 Sf(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Xr(r,...e){if(!yg(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function _f(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Sf(r.outputLen),Sf(r.blockLen)}function Yr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Bf(r,e){Xr(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var dr=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;function Cf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function On(r){return typeof r=="string"&&(r=Cf(r)),Xr(r),r}function ac(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xr(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 Jr=class{clone(){return this._cloneInto()}};function Xo(r){let e=n=>r().update(On(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Yo(r=32){if(dr&&typeof dr.getRandomValues=="function")return dr.getRandomValues(new Uint8Array(r));if(dr&&typeof dr.randomBytes=="function")return dr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function wg(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 If=(r,e,t)=>r&e^~r&t,kf=(r,e,t)=>r&e^r&t^e&t,Qr=class extends Jr{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){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=On(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){Yr(this),Bf(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;wg(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 Jo=BigInt(4294967295),cc=BigInt(32);function Tf(r,e=!1){return e?{h:Number(r&Jo),l:Number(r>>cc&Jo)}:{h:Number(r>>cc&Jo)|0,l:Number(r&Jo)|0}}function bg(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}=Tf(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var xg=(r,e)=>BigInt(r>>>0)<<cc|BigInt(e>>>0),vg=(r,e,t)=>r>>>t,Eg=(r,e,t)=>r<<32-t|e>>>t,Ag=(r,e,t)=>r>>>t|e<<32-t,Sg=(r,e,t)=>r<<32-t|e>>>t,_g=(r,e,t)=>r<<64-t|e>>>t-32,Bg=(r,e,t)=>r>>>t-32|e<<64-t,Cg=(r,e)=>e,Ig=(r,e)=>r,kg=(r,e,t)=>r<<t|e>>>32-t,Tg=(r,e,t)=>e<<t|r>>>32-t,Lg=(r,e,t)=>e<<t-32|r>>>64-t,Ng=(r,e,t)=>r<<t-32|e>>>64-t;function Pg(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Dg=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Rg=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Mg=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ug=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Og=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Fg=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Vg={fromBig:Tf,split:bg,toBig:xg,shrSH:vg,shrSL:Eg,rotrSH:Ag,rotrSL:Sg,rotrBH:_g,rotrBL:Bg,rotr32H:Cg,rotr32L:Ig,rotlSH:kg,rotlSL:Tg,rotlBH:Lg,rotlBL:Ng,add:Pg,add3L:Dg,add3H:Rg,add4L:Mg,add4H:Ug,add5H:Fg,add5L:Og},F=Vg;var[Hg,Kg]=F.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))),zt=new Uint32Array(80),Gt=new Uint32Array(80),lc=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: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 y=0;y<16;y++,t+=4)zt[y]=e.getUint32(t),Gt[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let x=zt[y-15]|0,A=Gt[y-15]|0,_=F.rotrSH(x,A,1)^F.rotrSH(x,A,8)^F.shrSH(x,A,7),v=F.rotrSL(x,A,1)^F.rotrSL(x,A,8)^F.shrSL(x,A,7),B=zt[y-2]|0,k=Gt[y-2]|0,Y=F.rotrSH(B,k,19)^F.rotrBH(B,k,61)^F.shrSH(B,k,6),H=F.rotrSL(B,k,19)^F.rotrBL(B,k,61)^F.shrSL(B,k,6),V=F.add4L(v,H,Gt[y-7],Gt[y-16]),D=F.add4H(V,_,Y,zt[y-7],zt[y-16]);zt[y]=D|0,Gt[y]=V|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:w,Hl:b}=this;for(let y=0;y<80;y++){let x=F.rotrSH(l,d,14)^F.rotrSH(l,d,18)^F.rotrBH(l,d,41),A=F.rotrSL(l,d,14)^F.rotrSL(l,d,18)^F.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=F.add5L(b,A,v,Kg[y],Gt[y]),k=F.add5H(B,w,x,_,Hg[y],zt[y]),Y=B|0,H=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),V=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),D=n&s^n&a^s&a,I=o&i^o&c^i&c;w=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=F.add(u|0,f|0,k|0,Y|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let N=F.add3L(Y,V,I);n=F.add3H(N,k,H,D),o=N|0}({h:n,l:o}=F.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=F.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=F.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=F.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=F.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=F.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:w,l:b}=F.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,w,b)}roundClean(){zt.fill(0),Gt.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=Xo(()=>new lc);var ts={};Re(ts,{aInRange:()=>qe,abool:()=>ot,abytes:()=>en,bitGet:()=>jg,bitLen:()=>dc,bitMask:()=>Vn,bitSet:()=>Zg,bytesToHex:()=>Bt,bytesToNumberBE:()=>Ct,bytesToNumberLE:()=>jt,concatBytes:()=>It,createHmacDrbg:()=>pc,ensureBytes:()=>ae,equalBytes:()=>Gg,hexToBytes:()=>mr,hexToNumber:()=>hc,inRange:()=>Fn,isBytes:()=>Wt,memoized:()=>yr,notImplemented:()=>Yg,numberToBytesBE:()=>Zt,numberToBytesLE:()=>gr,numberToHexUnpadded:()=>pr,numberToVarBytesBE:()=>zg,utf8ToBytes:()=>Wg,validateObject:()=>ht});var Qo=BigInt(0),es=BigInt(1),qg=BigInt(2);function Wt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function en(r){if(!Wt(r))throw new Error("Uint8Array expected")}function ot(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var $g=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){en(r);let e="";for(let t=0;t<r.length;t++)e+=$g[r[t]];return e}function pr(r){let e=r.toString(16);return e.length&1?"0"+e:e}function hc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}var _t={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nf(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t.A&&r<=_t.F)return r-(_t.A-10);if(r>=_t.a&&r<=_t.f)return r-(_t.a-10)}function mr(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("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=Nf(r.charCodeAt(s)),a=Nf(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 Ct(r){return hc(Bt(r))}function jt(r){return en(r),hc(Bt(Uint8Array.from(r).reverse()))}function Zt(r,e){return mr(r.toString(16).padStart(e*2,"0"))}function gr(r,e){return Zt(r,e).reverse()}function zg(r){return mr(pr(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=mr(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Wt(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+" of length "+t+" expected, got "+o);return n}function It(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];en(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 Gg(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 Wg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var uc=r=>typeof r=="bigint"&&Qo<=r;function Fn(r,e,t){return uc(r)&&uc(e)&&uc(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Fn(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function dc(r){let e;for(e=0;r>Qo;r>>=es,e+=1);return e}function jg(r,e){return r>>BigInt(e)&es}function Zg(r,e,t){return r|(t?es:Qo)<<BigInt(e)}var Vn=r=>(qg<<BigInt(r-1))-es,fc=r=>new Uint8Array(r),Pf=r=>Uint8Array.from(r);function pc(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=fc(r),o=fc(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=fc())=>{o=a(Pf([0]),l),n=a(),l.length!==0&&(o=a(Pf([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 Xg={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"||Wt(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 ht(r,e,t={}){let n=(o,s,i)=>{let a=Xg[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};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 Yg=()=>{throw new Error("not implemented")};function yr(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 ge=BigInt(0),se=BigInt(1),wr=BigInt(2),Jg=BigInt(3),mc=BigInt(4),Df=BigInt(5),Rf=BigInt(8),Qg=BigInt(9),e0=BigInt(16);function Q(r,e){let t=r%e;return t>=ge?t:e+t}function t0(r,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===se)return ge;let n=se;for(;e>ge;)e&se&&(n=n*r%t),r=r*r%t,e>>=se;return n}function ie(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function rs(r,e){if(r===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=Q(r,e),n=e,o=ge,s=se,i=se,a=ge;for(;t!==ge;){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!==se)throw new Error("invert: does not exist");return Q(o,e)}function r0(r){let e=(r-se)/wr,t,n,o;for(t=r-se,n=0;t%wr===ge;t/=wr,n++);for(o=wr;o<r&&t0(o,e,r)!==r-se;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+se)/mc;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+se)/wr;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,se<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function n0(r){if(r%mc===Jg){let e=(r+se)/mc;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%Rf===Df){let e=(r-Df)/Rf;return function(n,o){let s=n.mul(o,wr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,wr),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%e0,r0(r)}var Mf=(r,e)=>(Q(r,e)&se)===se,o0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=o0.reduce((n,o)=>(n[o]="function",n),e);return ht(r,t)}function s0(r,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return r.ONE;if(t===se)return e;let n=r.ONE,o=e;for(;t>ge;)t&se&&(n=r.mul(n,o)),o=r.sqr(o),t>>=se;return n}function i0(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 yc(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Xt(r,e,t=!1,n={}){if(r<=ge)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=yc(r,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Vn(o),ZERO:ge,ONE:se,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&se)===se,neg:c=>Q(-c,r),eql:(c,u)=>c===u,sqr:c=>Q(c*c,r),add:(c,u)=>Q(c+u,r),sub:(c,u)=>Q(c-u,r),mul:(c,u)=>Q(c*u,r),pow:(c,u)=>s0(a,c,u),div:(c,u)=>Q(c*rs(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>rs(c,r),sqrt:n.sqrt||(c=>(i||(i=n0(r)),i(a,c))),invertBatch:c=>i0(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?gr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return t?jt(c):Ct(c)}});return Object.freeze(a)}function Uf(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 wc(r){let e=Uf(r);return e+Math.ceil(e/2)}function Of(r,e,t=!1){let n=r.length,o=Uf(e),s=wc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ct(r):jt(r),a=Q(i,e-se)+se;return t?gr(a,o):Zt(a,o)}var Ff=BigInt(0),ns=BigInt(1);function bc(r,e){let t=e.negate();return r?t:e}function Vf(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function xc(r,e){Vf(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function c0(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function l0(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var vc=new WeakMap,Hf=new WeakMap;function Ec(r){return Hf.get(r)||1}function os(r,e){return{constTimeNegate:bc,hasPrecomputes(t){return Ec(t)!==1},unsafeLadder(t,n,o=r.ZERO){let s=t;for(;n>Ff;)n&ns&&(o=o.add(s)),s=s.double(),n>>=ns;return o},precomputeWindow(t,n){let{windows:o,windowSize:s}=xc(n,e),i=[],a=t,c=a;for(let u=0;u<o;u++){c=a,i.push(c);for(let f=1;f<s;f++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(t,n,o){let{windows:s,windowSize:i}=xc(t,e),a=r.ZERO,c=r.BASE,u=BigInt(2**t-1),f=2**t,l=BigInt(t);for(let d=0;d<s;d++){let h=d*i,p=Number(o&u);o>>=l,p>i&&(p-=f,o+=ns);let m=h,g=h+Math.abs(p)-1,w=d%2!==0,b=p<0;p===0?c=c.add(bc(w,n[m])):a=a.add(bc(b,n[g]))}return{p:a,f:c}},wNAFUnsafe(t,n,o,s=r.ZERO){let{windows:i,windowSize:a}=xc(t,e),c=BigInt(2**t-1),u=2**t,f=BigInt(t);for(let l=0;l<i;l++){let d=l*a;if(o===Ff)break;let h=Number(o&c);if(o>>=f,h>a&&(h-=u,o+=ns),h===0)continue;let p=n[d+Math.abs(h)-1];h<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(t,n,o){let s=vc.get(n);return s||(s=this.precomputeWindow(n,t),t!==1&&vc.set(n,o(s))),s},wNAFCached(t,n,o){let s=Ec(t);return this.wNAF(s,this.getPrecomputes(s,t,o),n)},wNAFCachedUnsafe(t,n,o,s){let i=Ec(t);return i===1?this.unsafeLadder(t,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,t,o),n,s)},setWindowSize(t,n){Vf(n,e),Hf.set(t,n),vc.delete(t)}}}function ss(r,e,t,n){if(c0(t,r),l0(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=dc(BigInt(t.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),u=Math.floor((e.BITS-1)/i)*i,f=o;for(let l=u;l>=0;l-=i){c.fill(o);for(let h=0;h<n.length;h++){let p=n[h],m=Number(p>>BigInt(l)&BigInt(a));c[m]=c[m].add(t[h])}let d=o;for(let h=c.length-1,p=o;h>0;h--)p=p.add(c[h]),d=d.add(p);if(f=f.add(d),l!==0)for(let h=0;h<i;h++)f=f.double()}return f}function Hn(r){return gc(r.Fp),ht(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var st=BigInt(0),$e=BigInt(1),is=BigInt(2),u0=BigInt(8),f0={zip215:!0};function h0(r){let e=Hn(r);return ht(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Kf(r){let e=h0(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=is<<BigInt(a*8)-$e,f=t.create,l=Xt(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,C)=>{if(ot("phflag",C),E.length||C)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){qe("coordinate "+S,E,st,u)}function g(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=yr((S,E)=>{let{ex:C,ey:L,ez:M}=S,U=S.is0();E==null&&(E=U?u0:t.inv(M));let K=f(C*E),$=f(L*E),O=f(M*E);if(U)return{x:st,y:$e};if(O!==$e)throw new Error("invZ was invalid");return{x:K,y:$}}),b=yr(S=>{let{a:E,d:C}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:L,ey:M,ez:U,et:K}=S,$=f(L*L),O=f(M*M),J=f(U*U),ne=f(J*J),be=f($*E),xe=f(J*f(be+O)),Ee=f(ne+f(C*f($*O)));if(xe!==Ee)throw new Error("bad point: equation left != right (1)");let Be=f(L*M),Ke=f(U*K);if(Be!==Ke)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(E,C,L,M){this.ex=E,this.ey=C,this.ez=L,this.et=M,m("x",E),m("y",C),m("z",L),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof y)throw new Error("extended point not allowed");let{x:C,y:L}=E||{};return m("x",C),m("y",L),new y(C,L,$e,f(C*L))}static normalizeZ(E){let C=t.invertBatch(E.map(L=>L.ez));return E.map((L,M)=>L.toAffine(C[M])).map(y.fromAffine)}static msm(E,C){return ss(y,l,E,C)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:C,ey:L,ez:M}=this,{ex:U,ey:K,ez:$}=E,O=f(C*$),J=f(U*M),ne=f(L*$),be=f(K*M);return O===J&&ne===be}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:C,ey:L,ez:M}=this,U=f(C*C),K=f(L*L),$=f(is*f(M*M)),O=f(E*U),J=C+L,ne=f(f(J*J)-U-K),be=O+K,xe=be-$,Ee=O-K,Be=f(ne*xe),Ke=f(be*Ee),De=f(ne*Ee),ft=f(xe*be);return new y(Be,Ke,ft,De)}add(E){g(E);let{a:C,d:L}=e,{ex:M,ey:U,ez:K,et:$}=this,{ex:O,ey:J,ez:ne,et:be}=E;if(C===BigInt(-1)){let Yu=f((U-M)*(J+O)),Ju=f((U+M)*(J-O)),za=f(Ju-Yu);if(za===st)return this.double();let Qu=f(K*is*be),ef=f($*is*ne),tf=ef+Qu,rf=Ju+Yu,nf=ef-Qu,vm=f(tf*za),Em=f(rf*nf),Am=f(tf*nf),Sm=f(za*rf);return new y(vm,Em,Sm,Am)}let xe=f(M*O),Ee=f(U*J),Be=f($*L*be),Ke=f(K*ne),De=f((M+U)*(O+J)-xe-Ee),ft=Ke-Be,bt=Ke+Be,Tn=f(Ee-C*xe),ym=f(De*ft),wm=f(bt*Tn),bm=f(De*Tn),xm=f(ft*bt);return new y(ym,wm,xm,bm)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,y.normalizeZ)}multiply(E){let C=E;qe("scalar",C,$e,n);let{p:L,f:M}=this.wNAF(C);return y.normalizeZ([L,M])[0]}multiplyUnsafe(E,C=y.ZERO){let L=E;return qe("scalar",L,st,n),L===st?A:this.is0()||L===$e?this:_.wNAFCachedUnsafe(this,L,y.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return w(this,E)}clearCofactor(){let{h:E}=e;return E===$e?this:this.multiplyUnsafe(E)}static fromHex(E,C=!1){let{d:L,a:M}=e,U=t.BYTES;E=ae("pointHex",E,U),ot("zip215",C);let K=E.slice(),$=E[U-1];K[U-1]=$&-129;let O=jt(K),J=C?u:t.ORDER;qe("pointHex.y",O,st,J);let ne=f(O*O),be=f(ne-$e),xe=f(L*ne-M),{isValid:Ee,value:Be}=d(be,xe);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let Ke=(Be&$e)===$e,De=($&128)!==0;if(!C&&Be===st&&De)throw new Error("Point.fromHex: x=0 and x_0=1");return De!==Ke&&(Be=f(-Be)),y.fromAffine({x:Be,y:O})}static fromPrivateKey(E){return k(E).point}toRawBytes(){let{x:E,y:C}=this.toAffine(),L=gr(C,t.BYTES);return L[L.length-1]|=E&$e?128:0,L}toHex(){return Bt(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,$e,f(e.Gx*e.Gy)),y.ZERO=new y(st,$e,$e,st);let{BASE:x,ZERO:A}=y,_=os(y,a*8);function v(S){return Q(S,n)}function B(S){return v(jt(S))}function k(S){let E=t.BYTES;S=ae("private key",S,E);let C=ae("hashed private key",s(S),2*E),L=h(C.slice(0,E)),M=C.slice(E,2*E),U=B(L),K=x.multiply(U),$=K.toRawBytes();return{head:L,prefix:M,scalar:U,point:K,pointBytes:$}}function Y(S){return k(S).pointBytes}function H(S=new Uint8Array,...E){let C=It(...E);return B(s(p(C,ae("context",S),!!o)))}function V(S,E,C={}){S=ae("message",S),o&&(S=o(S));let{prefix:L,scalar:M,pointBytes:U}=k(E),K=H(C.context,L,S),$=x.multiply(K).toRawBytes(),O=H(C.context,$,U,S),J=v(K+O*M);qe("signature.s",J,st,n);let ne=It($,gr(J,t.BYTES));return ae("result",ne,t.BYTES*2)}let D=f0;function I(S,E,C,L=D){let{context:M,zip215:U}=L,K=t.BYTES;S=ae("signature",S,2*K),E=ae("message",E),C=ae("publicKey",C,K),U!==void 0&&ot("zip215",U),o&&(E=o(E));let $=jt(S.slice(K,2*K)),O,J,ne;try{O=y.fromHex(C,U),J=y.fromHex(S.slice(0,K),U),ne=x.multiplyUnsafe($)}catch{return!1}if(!U&&O.isSmallOrder())return!1;let be=H(M,J.toRawBytes(),O.toRawBytes(),E);return J.add(O.multiplyUnsafe(be)).subtract(ne).clearCofactor().equals(y.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:Y,sign:V,verify:I,ExtendedPoint:y,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,E=y.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var Ac=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),qf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),$1=BigInt(0),d0=BigInt(1),$f=BigInt(2),z1=BigInt(3),p0=BigInt(5),m0=BigInt(8);function g0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ac,a=r*r%s*r%s,c=ie(a,$f,s)*a%s,u=ie(c,d0,s)*r%s,f=ie(u,p0,s)*u%s,l=ie(f,e,s)*f%s,d=ie(l,t,s)*l%s,h=ie(d,n,s)*d%s,p=ie(h,o,s)*h%s,m=ie(p,o,s)*h%s,g=ie(m,e,s)*f%s;return{pow_p_5_8:ie(g,$f,s)*r%s,b2:a}}function y0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function w0(r,e){let t=Ac,n=Q(e*e*e,t),o=Q(n*n*e,t),s=g0(r*o).pow_p_5_8,i=Q(r*n*s,t),a=Q(e*i*i,t),c=i,u=Q(i*qf,t),f=a===r,l=a===Q(-r,t),d=a===Q(-r*qf,t);return f&&(i=c),(l||d)&&(i=u),Mf(i,t)&&(i=Q(-i,t)),{isValid:f||l,value:i}}var b0=Xt(Ac,void 0,!0),x0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:b0,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:m0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Lf,randomBytes:Yo,adjustScalarBytes:y0,uvRatio:w0},Kn=Kf(x0);var as=32,cs=64,Sc=32;function zf(){let r=Kn.utils.randomPrivateKey(),e=Kn.getPublicKey(r);return{privateKey:v0(r,e),publicKey:e}}function Gf(r,e){let t=r.subarray(0,Sc);return Kn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Wf(r,e,t){return Kn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function v0(r,e){let t=new Uint8Array(cs);for(let n=0;n<Sc;n++)t[n]=r[n],t[Sc+n]=e[n];return t}var qn=class{type="Ed25519";raw;constructor(e){this.raw=us(e,as)}toMultihash(){return St.digest(dt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return Wf(this.raw,t,e)}},ls=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=us(e,cs),this.publicKey=new qn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return Gf(this.raw,e)}};function _c(r){return r=us(r,as),new qn(r)}async function Zf(){let{privateKey:r,publicKey:e}=zf();return new ls(r,e)}function us(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function fe(r=0){return new Uint8Array(r)}function Ce(r=0){return new Uint8Array(r)}var E0=Math.pow(2,7),A0=Math.pow(2,14),S0=Math.pow(2,21),Bc=Math.pow(2,28),Cc=Math.pow(2,35),Ic=Math.pow(2,42),kc=Math.pow(2,49),X=128,Ie=127;function pe(r){if(r<E0)return 1;if(r<A0)return 2;if(r<S0)return 3;if(r<Bc)return 4;if(r<Cc)return 5;if(r<Ic)return 6;if(r<kc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Tc(r,e,t=0){switch(pe(r)){case 8:e[t++]=r&255|X,r/=128;case 7:e[t++]=r&255|X,r/=128;case 6:e[t++]=r&255|X,r/=128;case 5:e[t++]=r&255|X,r/=128;case 4:e[t++]=r&255|X,r>>>=7;case 3:e[t++]=r&255|X,r>>>=7;case 2:e[t++]=r&255|X,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function _0(r,e,t=0){switch(pe(r)){case 8:e.set(t++,r&255|X),r/=128;case 7:e.set(t++,r&255|X),r/=128;case 6:e.set(t++,r&255|X),r/=128;case 5:e.set(t++,r&255|X),r/=128;case 4:e.set(t++,r&255|X),r>>>=7;case 3:e.set(t++,r&255|X),r>>>=7;case 2:e.set(t++,r&255|X),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Lc(r,e){let t=r[e],n=0;if(n+=t&Ie,t<X||(t=r[e+1],n+=(t&Ie)<<7,t<X)||(t=r[e+2],n+=(t&Ie)<<14,t<X)||(t=r[e+3],n+=(t&Ie)<<21,t<X)||(t=r[e+4],n+=(t&Ie)*Bc,t<X)||(t=r[e+5],n+=(t&Ie)*Cc,t<X)||(t=r[e+6],n+=(t&Ie)*Ic,t<X)||(t=r[e+7],n+=(t&Ie)*kc,t<X))return n;throw new RangeError("Could not decode varint")}function B0(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<X||(t=r.get(e+1),n+=(t&Ie)<<7,t<X)||(t=r.get(e+2),n+=(t&Ie)<<14,t<X)||(t=r.get(e+3),n+=(t&Ie)<<21,t<X)||(t=r.get(e+4),n+=(t&Ie)*Bc,t<X)||(t=r.get(e+5),n+=(t&Ie)*Cc,t<X)||(t=r.get(e+6),n+=(t&Ie)*Ic,t<X)||(t=r.get(e+7),n+=(t&Ie)*kc,t<X))return n;throw new RangeError("Could not decode varint")}function ke(r,e,t=0){return e==null&&(e=Ce(pe(r))),e instanceof Uint8Array?Tc(r,e,t):_0(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?Lc(r,e):B0(r,e)}var Nc=new Float32Array([-0]),Yt=new Uint8Array(Nc.buffer);function Xf(r,e,t){Nc[0]=r,e[t]=Yt[0],e[t+1]=Yt[1],e[t+2]=Yt[2],e[t+3]=Yt[3]}function Yf(r,e){return Yt[0]=r[e],Yt[1]=r[e+1],Yt[2]=r[e+2],Yt[3]=r[e+3],Nc[0]}var Pc=new Float64Array([-0]),Te=new Uint8Array(Pc.buffer);function Jf(r,e,t){Pc[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 Qf(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],Pc[0]}var C0=BigInt(Number.MAX_SAFE_INTEGER),I0=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 xr;if(e<C0&&e>I0)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>eh&&(o=0n,++n>eh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return xr;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):xr}},xr=new je(0,0);xr.toBigInt=function(){return 0n};xr.zzEncode=xr.zzDecode=function(){return this};xr.length=function(){return 1};var eh=4294967296n;function th(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 rh(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 Dc(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 fs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Rc=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 fs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return fs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=Yf(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=Qf(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 rh(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=fs(this.buf,this.pos+=4),t=fs(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=Lc(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 Mc(r){return new Rc(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=Mc(r);return e.decode(n,void 0,t)}var Uc={};Re(Uc,{base10:()=>k0});var k0=$t({prefix:"9",name:"base10",alphabet:"0123456789"});var Oc={};Re(Oc,{base16:()=>T0,base16upper:()=>L0});var T0=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L0=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Fc={};Re(Fc,{base2:()=>N0});var N0=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vc={};Re(Vc,{base256emoji:()=>U0});var oh=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}"),P0=oh.reduce((r,e,t)=>(r[t]=e,r),[]),D0=oh.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function R0(r){return r.reduce((e,t)=>(e+=P0[t],e),"")}function M0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=D0[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var U0=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:R0,decode:M0});var qc={};Re(qc,{base64:()=>Hc,base64pad:()=>O0,base64url:()=>Kc,base64urlpad:()=>F0});var Hc=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O0=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Kc=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),F0=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $c={};Re($c,{base8:()=>V0});var V0=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zc={};Re(zc,{identity:()=>H0});var H0=Gr({prefix:"\0",name:"identity",encode:r=>ff(r),decode:r=>uf(r)});var Sv=new TextEncoder,_v=new TextDecoder;var jc={};Re(jc,{sha256:()=>tn,sha512:()=>$0});function Wc({name:r,code:e,encode:t}){return new Gc(r,e,t)}var Gc=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 ih(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var tn=Wc({name:"sha2-256",code:18,encode:ih("SHA-256")}),$0=Wc({name:"sha2-512",code:19,encode:ih("SHA-512")});var $n={...zc,...Fc,...$c,...Uc,...Oc,...rc,...nc,...tc,...qc,...Vc},Uv={...jc,...ic};function ch(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ah=ch("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Zc=ch("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=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),z0={utf8:ah,"utf-8":ah,hex:$n.base16,latin1:Zc,ascii:Zc,binary:Zc,...$n},hs=z0;function P(r,e="utf8"){let t=hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Xc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ce(i);o+i>e&&(n=Ce(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var vr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Yc(){}var Qc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},G0=Xc();function W0(r){return globalThis.Buffer!=null?Ce(r):G0(r)}var Gn=class{len;head;tail;states;constructor(){this.len=0,this.head=new vr(Yc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new vr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new el((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(ds,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(ds,t.length(),t)}uint64Number(e){return this._push(Tc,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(ds,t.length(),t)}sint64Number(e){let t=je.fromNumber(e).zzEncode();return this._push(ds,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jc,1,e?1:0)}fixed32(e){return this._push(zn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=je.fromBigInt(e);return this._push(zn,4,t.lo)._push(zn,4,t.hi)}fixed64Number(e){let t=je.fromNumber(e);return this._push(zn,4,t.lo)._push(zn,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(Xf,4,e)}double(e){return this._push(Jf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Jc,1,0):this.uint32(t)._push(Z0,t,e)}string(e){let t=th(e);return t!==0?this.uint32(t)._push(Dc,t,e):this._push(Jc,1,0)}fork(){return this.states=new Qc(this),this.head=this.tail=new vr(Yc,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 vr(Yc,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=W0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Jc(r,e,t){e[t]=r&255}function j0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var el=class extends vr{next;constructor(e,t){super(j0,e,t),this.next=void 0}};function ds(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 zn(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 Z0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Gn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(X0,e,r),this},Gn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Y0,e,r),this});function X0(r,e,t){e.set(r,t)}function Y0(r,e,t){r.length<40?Dc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function tl(){return new Gn}function Ue(r,e){let t=tl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rn;(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"})(rn||(rn={}));function ps(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function rl(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 ps("enum",rn.VARINT,t,n)}function Oe(r,e){return ps("message",rn.LENGTH_DELIMITED,r,e)}var Er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Wn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ye;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ye||(ye={}));var nl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(nl||(nl={}));(function(r){r.codec=()=>rl(nl)})(ye||(ye={}));var pt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ye.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=ye.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(pt||(pt={}));var ol;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ye.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=ye.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(ol||(ol={}));var oo={};Re(oo,{MAX_RSA_KEY_SIZE:()=>li,generateRSAKeyPair:()=>wl,jwkToJWKKeyPair:()=>ud,jwkToPkcs1:()=>gy,jwkToPkix:()=>gl,jwkToRSAPrivateKey:()=>ld,pkcs1ToJwk:()=>id,pkcs1ToRSAPrivateKey:()=>cd,pkixToJwk:()=>ad,pkixToRSAPublicKey:()=>yl});function J0(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function sl(r,...e){if(!J0(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function il(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 uh(r,e){sl(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var gs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ct=(r,e)=>r<<32-e|r>>>e;function Q0(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function al(r){return typeof r=="string"&&(r=Q0(r)),sl(r),r}var ms=class{clone(){return this._cloneInto()}};function fh(r){let e=n=>r().update(al(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function hh(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 ey(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 dh=(r,e,t)=>r&e^~r&t,ph=(r,e,t)=>r&e^r&t^e&t,ys=class extends ms{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=gs(this.buffer)}update(e){il(this);let{view:t,buffer:n,blockLen:o}=this;e=al(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=gs(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){il(this),uh(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;ey(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(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 ty=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]),Jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qt=new Uint32Array(64),cl=class extends ys{constructor(){super(64,32,8,!1),this.A=Jt[0]|0,this.B=Jt[1]|0,this.C=Jt[2]|0,this.D=Jt[3]|0,this.E=Jt[4]|0,this.F=Jt[5]|0,this.G=Jt[6]|0,this.H=Jt[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)Qt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Qt[l-15],h=Qt[l-2],p=ct(d,7)^ct(d,18)^d>>>3,m=ct(h,17)^ct(h,19)^h>>>10;Qt[l]=m+Qt[l-7]+p+Qt[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=ct(a,6)^ct(a,11)^ct(a,25),h=f+d+dh(a,c,u)+ty[l]+Qt[l]|0,m=(ct(n,2)^ct(n,13)^ct(n,22))+ph(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(){Qt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ws=fh(()=>new cl);var q=hr(mh());function Sr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function er(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function vs(...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 ul(){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=Sr(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,Sr(s,8)-n}function gh(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function yh(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 ze(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 B2=Math.log(2);function Es(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function fl(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 Pt(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 Zn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return fl(this.items)}},jn=[new Uint8Array([1])],wh="0123456789";var cn="",lt=new ArrayBuffer(0),hl=new Uint8Array(0),Xn="EndOfContent",xh="OCTET STRING",vh="BIT STRING";function Dt(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):hl}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(!Pt(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",lt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Tt=class{constructor({blockLength:e=0,error:t=cn,warnings:n=[],valueBeforeDecode:o=hl}={}){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)}}};Tt.NAME="baseBlock";var Le=class extends Tt{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 As=class extends Dt(Tt){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):hl,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",lt}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=er(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(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=Sr(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}}};As.NAME="identificationBlock";var Ss=class extends Tt{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(!Pt(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=Sr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=er(this.length,8);if(o.byteLength>127)return this.error="Too big length",lt;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Ss.NAME="lengthBlock";var T={},Ae=class extends Tt{constructor({name:e=cn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new As(o),this.lenBlock=new Ss(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 Zn;t||Eh(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?lt:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():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 yh(t,n)}};Ae.NAME="BaseBlock";function Eh(r){if(r instanceof T.Constructed)for(let e of r.valueBlock.value)Eh(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var _s=class extends Ae{constructor({value:e=cn,...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}'`}};_s.NAME="BaseStringBlock";var Bs=class extends Dt(Le){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Bs.NAME="PrimitiveValueBlock";var Ah,Cs=class extends Ae{constructor(e={}){super(e,Bs),this.idBlock.isConstructed=!1}};Ah=Cs;T.Primitive=Ah;Cs.NAME="PRIMITIVE";function uy(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 ai(r,e=0,t=r.length){let n=e,o=new Ae({},Le),s=new Tt;if(!Pt(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=Ae;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=T.EndOfContent;break;case 1:c=T.Boolean;break;case 2:c=T.Integer;break;case 3:c=T.BitString;break;case 4:c=T.OctetString;break;case 5:c=T.Null;break;case 6:c=T.ObjectIdentifier;break;case 10:c=T.Enumerated;break;case 12:c=T.Utf8String;break;case 13:c=T.RelativeObjectIdentifier;break;case 14:c=T.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=T.Sequence;break;case 17:c=T.Set;break;case 18:c=T.NumericString;break;case 19:c=T.PrintableString;break;case 20:c=T.TeletexString;break;case 21:c=T.VideotexString;break;case 22:c=T.IA5String;break;case 23:c=T.UTCTime;break;case 24:c=T.GeneralizedTime;break;case 25:c=T.GraphicString;break;case 26:c=T.VisibleString;break;case 27:c=T.GeneralString;break;case 28:c=T.UniversalString;break;case 29:c=T.CharacterString;break;case 30:c=T.BmpString;break;case 31:c=T.DATE;break;case 32:c=T.TimeOfDay;break;case 33:c=T.DateTime;break;case 34:c=T.Duration;break;default:{let u=o.idBlock.isConstructed?new T.Constructed:new T.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?T.Constructed:T.Primitive}return o=uy(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 dl(r){if(!r.byteLength){let e=new Ae({},Le);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ai(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function fy(r,e){return r?1:e}var mt=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(!Pt(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(;fy(this.isIndefiniteForm,n)>0;){let i=ai(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===Xn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?lt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};mt.NAME="ConstructedValueBlock";var Sh,tr=class extends Ae{constructor(e={}){super(e,mt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
3
|
-
`).map(
|
|
2
|
+
"use strict";var Libp2P=(()=>{var Rm=Object.create;var Os=Object.defineProperty;var Mm=Object.getOwnPropertyDescriptor;var Um=Object.getOwnPropertyNames;var Om=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Qe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Re=(r,e)=>{for(var t in e)Os(r,t,{get:e[t],enumerable:!0})},ff=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Um(e))!Fm.call(r,s)&&s!==t&&Os(r,s,{get:()=>e[s],enumerable:!(n=Mm(e,s))||n.enumerable});return r};var hr=(r,e,t)=>(t=r!=null?Rm(Om(r)):{},ff(e||!r||!r.__esModule?Os(t,"default",{value:r,enumerable:!0}):t,r)),Vm=r=>ff(Os({},"__esModule",{value:!0}),r);var vh=Qe(sn=>{"use strict";var hy="[object ArrayBuffer]",Tt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===hy}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),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])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 s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},dl="string",dy=/^[0-9a-f\s]+$/i,py=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,my=/^[a-zA-Z0-9-_]+$/,Eo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Tt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},Xe=class{static toString(e,t=!1){let n=Tt.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},Ao=class r{static isHex(e){return typeof e===dl&&dy.test(e)}static isBase64(e){return typeof e===dl&&py.test(e)}static isBase64Url(e){return typeof e===dl&&my.test(e)}static ToString(e,t="utf8"){let n=Tt.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=Tt.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 Eo.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 Eo.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 s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Tt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Tt.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];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 s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,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,"")||""}};Ao.DEFAULT_UTF8_ENCODING="utf8";function gy(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function yy(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function wy(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}sn.BufferSourceConverter=Tt;sn.Convert=Ao;sn.assign=gy;sn.combine=yy;sn.isEqual=wy});var Od=Qe((PA,Tl)=>{"use strict";var Ky=Object.prototype.hasOwnProperty,He="~";function ps(){}Object.create&&(ps.prototype=Object.create(null),new ps().__proto__||(He=!1));function qy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ud(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new qy(t,n||r,s),i=He?He+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function gi(r,e){--r._eventsCount===0?r._events=new ps:delete r._events[e]}function Ne(){this._events=new ps,this._eventsCount=0}Ne.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ky.call(t,n)&&e.push(He?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ne.prototype.listeners=function(e){var t=He?He+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};Ne.prototype.listenerCount=function(e){var t=He?He+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ne.prototype.emit=function(e,t,n,s,o,i){var a=He?He+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,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,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,s);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 Ud(this,e,t,n,!1)};Ne.prototype.once=function(e,t,n){return Ud(this,e,t,n,!0)};Ne.prototype.removeListener=function(e,t,n,s){var o=He?He+e:e;if(!this._events[o])return this;if(!t)return gi(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&gi(this,o);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:gi(this,o)}return this};Ne.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&gi(this,t)):(this._events=new ps,this._eventsCount=0),this};Ne.prototype.off=Ne.prototype.removeListener;Ne.prototype.addListener=Ne.prototype.on;Ne.prefixed=He;Ne.EventEmitter=Ne;typeof Tl<"u"&&(Tl.exports=Ne)});var qd=Qe((rS,Kd)=>{Kd.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 s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var op=Qe((O8,sp)=>{"use strict";sp.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var fp=Qe((lp,up)=>{"use strict";var Si=op(),{hasOwnProperty:ap}=Object.prototype,{propertyIsEnumerable:pw}=Object,wn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),mw=lp,ip={concatArrays:!1,ignoreUndefined:!1},_i=r=>{let e=[];for(let t in r)ap.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)pw.call(r,n)&&e.push(n)}return e};function bn(r){return Array.isArray(r)?gw(r):Si(r)?yw(r):r}function gw(r){let e=r.slice(0,0);return _i(r).forEach(t=>{wn(e,t,bn(r[t]))}),e}function yw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return _i(r).forEach(t=>{wn(e,t,bn(r[t]))}),e}var cp=(r,e,t,n)=>(t.forEach(s=>{typeof e[s]>"u"&&n.ignoreUndefined||(s in r&&r[s]!==Object.getPrototypeOf(r)?wn(r,s,Ql(r[s],e[s],n)):wn(r,s,bn(e[s])))}),r),ww=(r,e,t)=>{let n=r.slice(0,0),s=0;return[r,e].forEach(o=>{let i=[];for(let a=0;a<o.length;a++)ap.call(o,a)&&(i.push(String(a)),o===r?wn(n,s++,o[a]):wn(n,s++,bn(o[a])));n=cp(n,o,_i(o).filter(a=>!i.includes(a)),t)}),n};function Ql(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?ww(r,e,t):!Si(e)||!Si(r)?bn(e):cp(r,e,_i(e),t)}up.exports=function(...r){let e=Ql(bn(ip),this!==mw&&this||{},ip),t={_:{}};for(let n of r)if(n!==void 0){if(!Si(n))throw new TypeError("`"+n+"` is not an Option Object");t=Ql(t,{_:n},e)}return t._}});var gp=Qe((ws,Ni)=>{(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 s(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function o(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=s(h,2246822507),h^=h>>>13,h=s(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,w=p,b=0,y=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=s(b,y),b=o(b,15),b=s(b,x),w^=b,w=o(w,13),w=s(w,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=s(b,y),b=o(b,15),b=s(b,x),w^=b}return w^=h.length,w=i(w),w>>>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,w=p,b=p,y=p,x=p,A=0,_=0,v=0,B=0,k=597399067,J=2869860233,H=951274213,V=2716044179,D=0;D<g;D=D+16)A=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,_=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,v=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,B=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,A=s(A,k),A=o(A,15),A=s(A,J),w^=A,w=o(w,19),w+=b,w=s(w,5)+1444728091,_=s(_,J),_=o(_,16),_=s(_,H),b^=_,b=o(b,17),b+=y,b=s(b,5)+197830471,v=s(v,H),v=o(v,17),v=s(v,V),y^=v,y=o(y,15),y+=x,y=s(y,5)+2530024501,B=s(B,V),B=o(B,18),B=s(B,k),x^=B,x=o(x,13),x+=w,x=s(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[D+14]<<16;case 14:B^=h[D+13]<<8;case 13:B^=h[D+12],B=s(B,V),B=o(B,18),B=s(B,k),x^=B;case 12:v^=h[D+11]<<24;case 11:v^=h[D+10]<<16;case 10:v^=h[D+9]<<8;case 9:v^=h[D+8],v=s(v,H),v=o(v,17),v=s(v,V),y^=v;case 8:_^=h[D+7]<<24;case 7:_^=h[D+6]<<16;case 6:_^=h[D+5]<<8;case 5:_^=h[D+4],_=s(_,J),_=o(_,16),_=s(_,H),b^=_;case 4:A^=h[D+3]<<24;case 3:A^=h[D+2]<<16;case 2:A^=h[D+1]<<8;case 1:A^=h[D],A=s(A,k),A=o(A,15),A=s(A,J),w^=A}return w^=h.length,b^=h.length,y^=h.length,x^=h.length,w+=b,w+=y,w+=x,b+=w,y+=w,x+=w,w=i(w),b=i(b),y=i(y),x=i(x),w+=b,w+=y,w+=x,b+=w,y+=w,x+=w,("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(y>>>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,w=[0,p],b=[0,p],y=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)y=[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],y=c(y,A),y=u(y,31),y=c(y,_),w=l(w,y),w=u(w,27),w=a(w,b),w=a(c(w,[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,w),b=a(c(b,[0,5]),[0,944331445]);switch(y=[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:y=l(y,f([0,h[v+7]],56));case 7:y=l(y,f([0,h[v+6]],48));case 6:y=l(y,f([0,h[v+5]],40));case 5:y=l(y,f([0,h[v+4]],32));case 4:y=l(y,f([0,h[v+3]],24));case 3:y=l(y,f([0,h[v+2]],16));case 2:y=l(y,f([0,h[v+1]],8));case 1:y=l(y,[0,h[v]]),y=c(y,A),y=u(y,31),y=c(y,_),w=l(w,y)}return w=l(w,[0,h.length]),b=l(b,[0,h.length]),w=a(w,b),b=a(b,w),w=d(w),b=d(b),w=a(w,b),b=a(b,w),("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof ws<"u"?(typeof Ni<"u"&&Ni.exports&&(ws=Ni.exports=t),ws.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)})(ws)});var wp=Qe((h_,yp)=>{yp.exports=gp()});var Vp=Qe(_s=>{(function(){var r,e,t,n,s,o,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"),o=t("a"),s=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])-o)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-s)>>>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}(),_s.ip2long=i,_s.long2ip=a,_s.Netmask=r}).call(_s)});var fm=Qe((zB,um)=>{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))}um.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 s=this._errors[n],o=s.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=s,t=i)}return e}});var hm=Qe(Fr=>{var Qb=fm();Fr.operation=function(r){var e=Fr.timeouts(r);return new Qb(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Fr.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=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(o,i){return o-i}),n};Fr.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};Fr.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 s=0;s<t.length;s++){var o=t[s],i=r[o];r[o]=function(c){var u=Fr.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[o].options=e}}});var pm=Qe((WB,dm)=>{dm.exports=hm()});var Ix={};Re(Ix,{createLibp2p:()=>Cx});var hf=Symbol.for("@libp2p/connection");var Xa=Symbol.for("@libp2p/content-routing");var Ya=Symbol.for("@libp2p/peer-discovery");var Fs=Symbol.for("@libp2p/peer-id");function Vs(r){return!!r?.[Fs]}var Ja=Symbol.for("@libp2p/peer-routing");var Qa="keep-alive";var Mx=Symbol.for("@libp2p/transport");var Kt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Kt||(Kt={}));var et=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Kr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Pn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Hs=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},qr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Ks=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},$r=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},qt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},qs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},$s=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Dn=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},zs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Gs=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},vt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var zr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Gr=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ws=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},js=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},$t=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var se=(r,...e)=>{try{[...e]}catch{}};var Et=class extends EventTarget{#e=new Map;constructor(){super(),se(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 s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function Zs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function df(...r){let e=[];for(let t of r)Zs(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 pf(...r){let e=[];for(let t of r)Zs(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 Rn=Symbol.for("@libp2p/service-capabilities"),ec=Symbol.for("@libp2p/service-dependencies");var oc={};Re(oc,{base58btc:()=>X,base58flickr:()=>Gm});var h1=new Uint8Array(0);function mf(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 At(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 gf(r){return new TextEncoder().encode(r)}function yf(r){return new TextDecoder().decode(r)}function Hm(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 s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}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,w=0,b=p.length;w!==b&&p[w]===0;)w++,m++;for(var y=(b-w)*f+1>>>0,x=new Uint8Array(y);w!==b;){for(var A=p[w],_=0,v=y-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=_,w++}for(var B=y-g;B!==y&&x[B]===0;)B++;for(var k=c.repeat(m);B<y;++B)k+=r.charAt(x[B]);return k}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,w=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,y=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<w)&&_!==-1;_--,A++)x+=a*y[_]>>>0,y[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");w=A,m++}if(p[m]!==" "){for(var v=b-w;v!==b&&y[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),k=g;v!==b;)B[k++]=y[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 Km=Hm,qm=Km,bf=qm;var tc=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")}},rc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 xf(this,e)}},nc=class{decoders;constructor(e){this.decoders=e}or(e){return xf(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 xf(r,e){return new nc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var sc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new tc(e,t,n),this.decoder=new rc(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Wr({name:r,prefix:e,encode:t,decode:n}){return new sc(r,e,t,n)}function zt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bf(t,r);return Wr({prefix:e,name:r,encode:n,decode:o=>At(s(o))})}function $m(r,e,t,n){let s={};for(let f=0;f<e.length;++f)s[e[f]]=f;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,u=0;for(let f=0;f<o;++f){let l=s[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 zm(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;o.length*t&7;)o+="=";return o}function le({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Wr({prefix:e,name:r,encode(s){return zm(s,n,t)},decode(s){return $m(s,n,t,r)}})}var X=zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gm=zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ic={};Re(ic,{base32:()=>We,base32hex:()=>Xm,base32hexpad:()=>Jm,base32hexpadupper:()=>Qm,base32hexupper:()=>Ym,base32pad:()=>jm,base32padupper:()=>Zm,base32upper:()=>Wm,base32z:()=>eg});var We=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wm=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jm=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zm=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xm=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ym=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jm=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qm=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eg=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ac={};Re(ac,{base36:()=>Mn,base36upper:()=>tg});var Mn=zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tg=zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rg=Af,vf=128,ng=127,sg=~ng,og=Math.pow(2,31);function Af(r,e,t){e=e||[],t=t||0;for(var n=t;r>=og;)e[t++]=r&255|vf,r/=128;for(;r&sg;)e[t++]=r&255|vf,r>>>=7;return e[t]=r|0,Af.bytes=t-n+1,e}var ig=cc,ag=128,Ef=127;function cc(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw cc.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Ef)<<s:(i&Ef)*Math.pow(2,s),s+=7}while(i>=ag);return cc.bytes=o-n,t}var cg=Math.pow(2,7),lg=Math.pow(2,14),ug=Math.pow(2,21),fg=Math.pow(2,28),hg=Math.pow(2,35),dg=Math.pow(2,42),pg=Math.pow(2,49),mg=Math.pow(2,56),gg=Math.pow(2,63),yg=function(r){return r<cg?1:r<lg?2:r<ug?3:r<fg?4:r<hg?5:r<dg?6:r<pg?7:r<mg?8:r<gg?9:10},wg={encode:rg,decode:ig,encodingLength:yg},bg=wg,Un=bg;function On(r,e=0){return[Un.decode(r,e),Un.decode.bytes]}function jr(r,e,t=0){return Un.encode(r,e,t),e}function Zr(r){return Un.encodingLength(r)}function tt(r,e){let t=e.byteLength,n=Zr(r),s=n+Zr(t),o=new Uint8Array(s+t);return jr(r,o,0),jr(t,o,n),o.set(e,s),new Xr(r,t,e,o)}function rt(r){let e=At(r),[t,n]=On(e),[s,o]=On(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Xr(t,s,i,e)}function Sf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&mf(r.bytes,t.bytes)}}var Xr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function _f(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return vg(t,lc(r),e??X.encoder);default:return Eg(t,lc(r),e??We.encoder)}}var Bf=new WeakMap;function lc(r){let e=Bf.get(r);if(e==null){let t=new Map;return Bf.set(r,t),t}return e}var me=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ag)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&&Sf(e.multihash,n.multihash)}toString(e){return _f(this,e)}toJSON(){return{"/":_f(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:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Cf(n,s,o.bytes))}else if(t[Sg]===!0){let{version:n,multihash:s,code:o}=t,i=rt(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Cf(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=At(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Xr(t.multihashCode,t.digestSize,o,s);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]=On(e.subarray(t));return t+=d,l},s=n(),o=Fn;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,s]=xg(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lc(o).set(n,e),o}};function xg(r,e){switch(r[0]){case"Q":{let t=e??X;return[X.prefix,t.decode(`${X.prefix}${r}`)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Mn.prefix:{let t=e??Mn;return[Mn.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 vg(r,e,t){let{prefix:n}=t;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Eg(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Fn=112,Ag=18;function Cf(r,e,t){let n=Zr(r),s=n+Zr(e),o=new Uint8Array(s+t.byteLength);return jr(r,o,0),jr(e,o,n),o.set(t,s),o}var Sg=Symbol.for("@ipld/js-cid/CID");var uc={};Re(uc,{identity:()=>_t});var If=0,_g="identity",kf=At;function Bg(r){return tt(If,kf(r))}var _t={code:If,name:_g,encode:kf,digest:Bg};function ue(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, got "+r)}function Cg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Yr(r,...e){if(!Cg(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Lf(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 Jr(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){Yr(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var dr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Ys=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),nt=(r,e)=>r<<32-e|r>>>e;function Pf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Vn(r){return typeof r=="string"&&(r=Pf(r)),Yr(r),r}function fc(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Yr(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}var Qr=class{clone(){return this._cloneInto()}};function Js(r){let e=n=>r().update(Vn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Qs(r=32){if(dr&&typeof dr.getRandomValues=="function")return dr.getRandomValues(new Uint8Array(r));if(dr&&typeof dr.randomBytes=="function")return dr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Ig(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(t>>s&o),a=Number(t&o),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Df=(r,e,t)=>r&e^~r&t,Rf=(r,e,t)=>r&e^r&t^e&t,en=class extends Qr{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ys(this.buffer)}update(e){Jr(this);let{view:t,buffer:n,blockLen:s}=this;e=Vn(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Ys(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Jr(this),Nf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let l=i;l<s;l++)t[l]=0;Ig(n,s-8,BigInt(this.length*8),o),this.process(n,0);let a=Ys(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],o)}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:s,finished:o,destroyed:i,pos:a}=this;return e.length=s,e.pos=a,e.finished=o,e.destroyed=i,s%t&&e.buffer.set(n),e}};var eo=BigInt(4294967295),hc=BigInt(32);function Mf(r,e=!1){return e?{h:Number(r&eo),l:Number(r>>hc&eo)}:{h:Number(r>>hc&eo)|0,l:Number(r&eo)|0}}function kg(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let s=0;s<r.length;s++){let{h:o,l:i}=Mf(r[s],e);[t[s],n[s]]=[o,i]}return[t,n]}var Tg=(r,e)=>BigInt(r>>>0)<<hc|BigInt(e>>>0),Lg=(r,e,t)=>r>>>t,Ng=(r,e,t)=>r<<32-t|e>>>t,Pg=(r,e,t)=>r>>>t|e<<32-t,Dg=(r,e,t)=>r<<32-t|e>>>t,Rg=(r,e,t)=>r<<64-t|e>>>t-32,Mg=(r,e,t)=>r>>>t-32|e<<64-t,Ug=(r,e)=>e,Og=(r,e)=>r,Fg=(r,e,t)=>r<<t|e>>>32-t,Vg=(r,e,t)=>e<<t|r>>>32-t,Hg=(r,e,t)=>e<<t-32|r>>>64-t,Kg=(r,e,t)=>r<<t-32|e>>>64-t;function qg(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var $g=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),zg=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gg=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Wg=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,jg=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Zg=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Xg={fromBig:Mf,split:kg,toBig:Tg,shrSH:Lg,shrSL:Ng,rotrSH:Pg,rotrSL:Dg,rotrBH:Rg,rotrBL:Mg,rotr32H:Ug,rotr32L:Og,rotlSH:Fg,rotlSL:Vg,rotlBH:Hg,rotlBL:Kg,add:qg,add3L:$g,add3H:zg,add4L:Gg,add4H:Wg,add5H:Zg,add5L:jg},F=Xg;var[Yg,Jg]=F.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))),Gt=new Uint32Array(80),Wt=new Uint32Array(80),dc=class extends en{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:s,Ch:o,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,s,o,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,s,o,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=s|0,this.Ch=o|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 y=0;y<16;y++,t+=4)Gt[y]=e.getUint32(t),Wt[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let x=Gt[y-15]|0,A=Wt[y-15]|0,_=F.rotrSH(x,A,1)^F.rotrSH(x,A,8)^F.shrSH(x,A,7),v=F.rotrSL(x,A,1)^F.rotrSL(x,A,8)^F.shrSL(x,A,7),B=Gt[y-2]|0,k=Wt[y-2]|0,J=F.rotrSH(B,k,19)^F.rotrBH(B,k,61)^F.shrSH(B,k,6),H=F.rotrSL(B,k,19)^F.rotrBL(B,k,61)^F.shrSL(B,k,6),V=F.add4L(v,H,Wt[y-7],Wt[y-16]),D=F.add4H(V,_,J,Gt[y-7],Gt[y-16]);Gt[y]=D|0,Wt[y]=V|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:w,Hl:b}=this;for(let y=0;y<80;y++){let x=F.rotrSH(l,d,14)^F.rotrSH(l,d,18)^F.rotrBH(l,d,41),A=F.rotrSL(l,d,14)^F.rotrSL(l,d,18)^F.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=F.add5L(b,A,v,Jg[y],Wt[y]),k=F.add5H(B,w,x,_,Yg[y],Gt[y]),J=B|0,H=F.rotrSH(n,s,28)^F.rotrBH(n,s,34)^F.rotrBH(n,s,39),V=F.rotrSL(n,s,28)^F.rotrBL(n,s,34)^F.rotrBL(n,s,39),D=n&o^n&a^o&a,I=s&i^s&c^i&c;w=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=F.add(u|0,f|0,k|0,J|0),u=a|0,f=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let N=F.add3L(J,V,I);n=F.add3H(N,k,H,D),s=N|0}({h:n,l:s}=F.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=F.add(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=F.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=F.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=F.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=F.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:w,l:b}=F.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,s,o,i,a,c,u,f,l,d,h,p,m,g,w,b)}roundClean(){Gt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Uf=Js(()=>new dc);var no={};Re(no,{aInRange:()=>qe,abool:()=>st,abytes:()=>tn,bitGet:()=>s0,bitLen:()=>yc,bitMask:()=>Kn,bitSet:()=>o0,bytesToHex:()=>Ct,bytesToNumberBE:()=>It,bytesToNumberLE:()=>Zt,concatBytes:()=>kt,createHmacDrbg:()=>wc,ensureBytes:()=>ae,equalBytes:()=>r0,hexToBytes:()=>mr,hexToNumber:()=>gc,inRange:()=>Hn,isBytes:()=>jt,memoized:()=>yr,notImplemented:()=>a0,numberToBytesBE:()=>Xt,numberToBytesLE:()=>gr,numberToHexUnpadded:()=>pr,numberToVarBytesBE:()=>t0,utf8ToBytes:()=>n0,validateObject:()=>dt});var to=BigInt(0),ro=BigInt(1),Qg=BigInt(2);function jt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function tn(r){if(!jt(r))throw new Error("Uint8Array expected")}function st(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var e0=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ct(r){tn(r);let e="";for(let t=0;t<r.length;t++)e+=e0[r[t]];return e}function pr(r){let e=r.toString(16);return e.length&1?"0"+e:e}function gc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?to:BigInt("0x"+r)}var Bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Of(r){if(r>=Bt._0&&r<=Bt._9)return r-Bt._0;if(r>=Bt.A&&r<=Bt.F)return r-(Bt.A-10);if(r>=Bt.a&&r<=Bt.f)return r-(Bt.a-10)}function mr(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("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Of(r.charCodeAt(o)),a=Of(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function It(r){return gc(Ct(r))}function Zt(r){return tn(r),gc(Ct(Uint8Array.from(r).reverse()))}function Xt(r,e){return mr(r.toString(16).padStart(e*2,"0"))}function gr(r,e){return Xt(r,e).reverse()}function t0(r){return mr(pr(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=mr(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(jt(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let s=n.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return n}function kt(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];tn(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function r0(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 n0(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var pc=r=>typeof r=="bigint"&&to<=r;function Hn(r,e,t){return pc(r)&&pc(e)&&pc(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Hn(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function yc(r){let e;for(e=0;r>to;r>>=ro,e+=1);return e}function s0(r,e){return r>>BigInt(e)&ro}function o0(r,e,t){return r|(t?ro:to)<<BigInt(e)}var Kn=r=>(Qg<<BigInt(r-1))-ro,mc=r=>new Uint8Array(r),Ff=r=>Uint8Array.from(r);function wc(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=mc(r),s=mc(r),o=0,i=()=>{n.fill(1),s.fill(0),o=0},a=(...l)=>t(s,n,...l),c=(l=mc())=>{s=a(Ff([0]),l),n=a(),l.length!==0&&(s=a(Ff([1]),l),n=a())},u=()=>{if(o++>=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 kt(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var i0={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"||jt(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 dt(r,e,t={}){let n=(s,o,i)=>{let a=i0[o];if(typeof a!="function")throw new Error("invalid validator function");let c=r[s];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(s)+" is invalid. Expected "+o+", got "+c)};for(let[s,o]of Object.entries(e))n(s,o,!1);for(let[s,o]of Object.entries(t))n(s,o,!0);return r}var a0=()=>{throw new Error("not implemented")};function yr(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var ge=BigInt(0),oe=BigInt(1),wr=BigInt(2),c0=BigInt(3),bc=BigInt(4),Vf=BigInt(5),Hf=BigInt(8),l0=BigInt(9),u0=BigInt(16);function ee(r,e){let t=r%e;return t>=ge?t:e+t}function f0(r,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===oe)return ge;let n=oe;for(;e>ge;)e&oe&&(n=n*r%t),r=r*r%t,e>>=oe;return n}function ie(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function so(r,e){if(r===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=ee(r,e),n=e,s=ge,o=oe,i=oe,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=s-i*u,d=o-a*u;n=t,t=f,s=i,o=a,i=l,a=d}if(n!==oe)throw new Error("invert: does not exist");return ee(s,e)}function h0(r){let e=(r-oe)/wr,t,n,s;for(t=r-oe,n=0;t%wr===ge;t/=wr,n++);for(s=wr;s<r&&f0(s,e,r)!==r-oe;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+oe)/bc;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 o=(t+oe)/wr;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,s),t),l=a.pow(c,o),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,oe<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function d0(r){if(r%bc===c0){let e=(r+oe)/bc;return function(n,s){let o=n.pow(s,e);if(!n.eql(n.sqr(o),s))throw new Error("Cannot find square root");return o}}if(r%Hf===Vf){let e=(r-Vf)/Hf;return function(n,s){let o=n.mul(s,wr),i=n.pow(o,e),a=n.mul(s,i),c=n.mul(n.mul(a,wr),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),s))throw new Error("Cannot find square root");return u}}return r%u0,h0(r)}var Kf=(r,e)=>(ee(r,e)&oe)===oe,p0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=p0.reduce((n,s)=>(n[s]="function",n),e);return dt(r,t)}function m0(r,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return r.ONE;if(t===oe)return e;let n=r.ONE,s=e;for(;t>ge;)t&oe&&(n=r.mul(n,s)),s=r.sqr(s),t>>=oe;return n}function g0(r,e){let t=new Array(e.length),n=e.reduce((o,i,a)=>r.is0(i)?o:(t[a]=o,r.mul(o,i)),r.ONE),s=r.inv(n);return e.reduceRight((o,i,a)=>r.is0(i)?o:(t[a]=r.mul(o,t[a]),r.mul(o,i)),s),t}function vc(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Yt(r,e,t=!1,n={}){if(r<=ge)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:s,nByteLength:o}=vc(r,e);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,BITS:s,BYTES:o,MASK:Kn(s),ZERO:ge,ONE:oe,create:c=>ee(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&oe)===oe,neg:c=>ee(-c,r),eql:(c,u)=>c===u,sqr:c=>ee(c*c,r),add:(c,u)=>ee(c+u,r),sub:(c,u)=>ee(c-u,r),mul:(c,u)=>ee(c*u,r),pow:(c,u)=>m0(a,c,u),div:(c,u)=>ee(c*so(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>so(c,r),sqrt:n.sqrt||(c=>(i||(i=d0(r)),i(a,c))),invertBatch:c=>g0(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?gr(c,o):Xt(c,o),fromBytes:c=>{if(c.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+c.length);return t?Zt(c):It(c)}});return Object.freeze(a)}function qf(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 Ec(r){let e=qf(r);return e+Math.ceil(e/2)}function $f(r,e,t=!1){let n=r.length,s=qf(e),o=Ec(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?It(r):Zt(r),a=ee(i,e-oe)+oe;return t?gr(a,s):Xt(a,s)}var zf=BigInt(0),oo=BigInt(1);function Ac(r,e){let t=e.negate();return r?t:e}function Gf(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Sc(r,e){Gf(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function w0(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function b0(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var _c=new WeakMap,Wf=new WeakMap;function Bc(r){return Wf.get(r)||1}function io(r,e){return{constTimeNegate:Ac,hasPrecomputes(t){return Bc(t)!==1},unsafeLadder(t,n,s=r.ZERO){let o=t;for(;n>zf;)n&oo&&(s=s.add(o)),o=o.double(),n>>=oo;return s},precomputeWindow(t,n){let{windows:s,windowSize:o}=Sc(n,e),i=[],a=t,c=a;for(let u=0;u<s;u++){c=a,i.push(c);for(let f=1;f<o;f++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(t,n,s){let{windows:o,windowSize:i}=Sc(t,e),a=r.ZERO,c=r.BASE,u=BigInt(2**t-1),f=2**t,l=BigInt(t);for(let d=0;d<o;d++){let h=d*i,p=Number(s&u);s>>=l,p>i&&(p-=f,s+=oo);let m=h,g=h+Math.abs(p)-1,w=d%2!==0,b=p<0;p===0?c=c.add(Ac(w,n[m])):a=a.add(Ac(b,n[g]))}return{p:a,f:c}},wNAFUnsafe(t,n,s,o=r.ZERO){let{windows:i,windowSize:a}=Sc(t,e),c=BigInt(2**t-1),u=2**t,f=BigInt(t);for(let l=0;l<i;l++){let d=l*a;if(s===zf)break;let h=Number(s&c);if(s>>=f,h>a&&(h-=u,s+=oo),h===0)continue;let p=n[d+Math.abs(h)-1];h<0&&(p=p.negate()),o=o.add(p)}return o},getPrecomputes(t,n,s){let o=_c.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&_c.set(n,s(o))),o},wNAFCached(t,n,s){let o=Bc(t);return this.wNAF(o,this.getPrecomputes(o,t,s),n)},wNAFCachedUnsafe(t,n,s,o){let i=Bc(t);return i===1?this.unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,s),n,o)},setWindowSize(t,n){Gf(n,e),Wf.set(t,n),_c.delete(t)}}}function ao(r,e,t,n){if(w0(t,r),b0(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,o=yc(BigInt(t.length)),i=o>12?o-3:o>4?o-2:o?2:1,a=(1<<i)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/i)*i,f=s;for(let l=u;l>=0;l-=i){c.fill(s);for(let h=0;h<n.length;h++){let p=n[h],m=Number(p>>BigInt(l)&BigInt(a));c[m]=c[m].add(t[h])}let d=s;for(let h=c.length-1,p=s;h>0;h--)p=p.add(c[h]),d=d.add(p);if(f=f.add(d),l!==0)for(let h=0;h<i;h++)f=f.double()}return f}function qn(r){return xc(r.Fp),dt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ot=BigInt(0),$e=BigInt(1),co=BigInt(2),x0=BigInt(8),v0={zip215:!0};function E0(r){let e=qn(r);return dt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function jf(r){let e=E0(r),{Fp:t,n,prehash:s,hash:o,randomBytes:i,nByteLength:a,h:c}=e,u=co<<BigInt(a*8)-$e,f=t.create,l=Yt(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:ot}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,C)=>{if(st("phflag",C),E.length||C)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){qe("coordinate "+S,E,ot,u)}function g(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=yr((S,E)=>{let{ex:C,ey:L,ez:M}=S,U=S.is0();E==null&&(E=U?x0:t.inv(M));let K=f(C*E),$=f(L*E),O=f(M*E);if(U)return{x:ot,y:$e};if(O!==$e)throw new Error("invZ was invalid");return{x:K,y:$}}),b=yr(S=>{let{a:E,d:C}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:L,ey:M,ez:U,et:K}=S,$=f(L*L),O=f(M*M),Q=f(U*U),ne=f(Q*Q),be=f($*E),xe=f(Q*f(be+O)),Ee=f(ne+f(C*f($*O)));if(xe!==Ee)throw new Error("bad point: equation left != right (1)");let Be=f(L*M),Ke=f(U*K);if(Be!==Ke)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(E,C,L,M){this.ex=E,this.ey=C,this.ez=L,this.et=M,m("x",E),m("y",C),m("z",L),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof y)throw new Error("extended point not allowed");let{x:C,y:L}=E||{};return m("x",C),m("y",L),new y(C,L,$e,f(C*L))}static normalizeZ(E){let C=t.invertBatch(E.map(L=>L.ez));return E.map((L,M)=>L.toAffine(C[M])).map(y.fromAffine)}static msm(E,C){return ao(y,l,E,C)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:C,ey:L,ez:M}=this,{ex:U,ey:K,ez:$}=E,O=f(C*$),Q=f(U*M),ne=f(L*$),be=f(K*M);return O===Q&&ne===be}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:C,ey:L,ez:M}=this,U=f(C*C),K=f(L*L),$=f(co*f(M*M)),O=f(E*U),Q=C+L,ne=f(f(Q*Q)-U-K),be=O+K,xe=be-$,Ee=O-K,Be=f(ne*xe),Ke=f(be*Ee),De=f(ne*Ee),ht=f(xe*be);return new y(Be,Ke,ht,De)}add(E){g(E);let{a:C,d:L}=e,{ex:M,ey:U,ez:K,et:$}=this,{ex:O,ey:Q,ez:ne,et:be}=E;if(C===BigInt(-1)){let nf=f((U-M)*(Q+O)),sf=f((U+M)*(Q-O)),Za=f(sf-nf);if(Za===ot)return this.double();let of=f(K*co*be),af=f($*co*ne),cf=af+of,lf=sf+nf,uf=af-of,Lm=f(cf*Za),Nm=f(lf*uf),Pm=f(cf*uf),Dm=f(Za*lf);return new y(Lm,Nm,Dm,Pm)}let xe=f(M*O),Ee=f(U*Q),Be=f($*L*be),Ke=f(K*ne),De=f((M+U)*(O+Q)-xe-Ee),ht=Ke-Be,xt=Ke+Be,Nn=f(Ee-C*xe),Cm=f(De*ht),Im=f(xt*Nn),km=f(De*Nn),Tm=f(ht*xt);return new y(Cm,Im,Tm,km)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,y.normalizeZ)}multiply(E){let C=E;qe("scalar",C,$e,n);let{p:L,f:M}=this.wNAF(C);return y.normalizeZ([L,M])[0]}multiplyUnsafe(E,C=y.ZERO){let L=E;return qe("scalar",L,ot,n),L===ot?A:this.is0()||L===$e?this:_.wNAFCachedUnsafe(this,L,y.normalizeZ,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return w(this,E)}clearCofactor(){let{h:E}=e;return E===$e?this:this.multiplyUnsafe(E)}static fromHex(E,C=!1){let{d:L,a:M}=e,U=t.BYTES;E=ae("pointHex",E,U),st("zip215",C);let K=E.slice(),$=E[U-1];K[U-1]=$&-129;let O=Zt(K),Q=C?u:t.ORDER;qe("pointHex.y",O,ot,Q);let ne=f(O*O),be=f(ne-$e),xe=f(L*ne-M),{isValid:Ee,value:Be}=d(be,xe);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let Ke=(Be&$e)===$e,De=($&128)!==0;if(!C&&Be===ot&&De)throw new Error("Point.fromHex: x=0 and x_0=1");return De!==Ke&&(Be=f(-Be)),y.fromAffine({x:Be,y:O})}static fromPrivateKey(E){return k(E).point}toRawBytes(){let{x:E,y:C}=this.toAffine(),L=gr(C,t.BYTES);return L[L.length-1]|=E&$e?128:0,L}toHex(){return Ct(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,$e,f(e.Gx*e.Gy)),y.ZERO=new y(ot,$e,$e,ot);let{BASE:x,ZERO:A}=y,_=io(y,a*8);function v(S){return ee(S,n)}function B(S){return v(Zt(S))}function k(S){let E=t.BYTES;S=ae("private key",S,E);let C=ae("hashed private key",o(S),2*E),L=h(C.slice(0,E)),M=C.slice(E,2*E),U=B(L),K=x.multiply(U),$=K.toRawBytes();return{head:L,prefix:M,scalar:U,point:K,pointBytes:$}}function J(S){return k(S).pointBytes}function H(S=new Uint8Array,...E){let C=kt(...E);return B(o(p(C,ae("context",S),!!s)))}function V(S,E,C={}){S=ae("message",S),s&&(S=s(S));let{prefix:L,scalar:M,pointBytes:U}=k(E),K=H(C.context,L,S),$=x.multiply(K).toRawBytes(),O=H(C.context,$,U,S),Q=v(K+O*M);qe("signature.s",Q,ot,n);let ne=kt($,gr(Q,t.BYTES));return ae("result",ne,t.BYTES*2)}let D=v0;function I(S,E,C,L=D){let{context:M,zip215:U}=L,K=t.BYTES;S=ae("signature",S,2*K),E=ae("message",E),C=ae("publicKey",C,K),U!==void 0&&st("zip215",U),s&&(E=s(E));let $=Zt(S.slice(K,2*K)),O,Q,ne;try{O=y.fromHex(C,U),Q=y.fromHex(S.slice(0,K),U),ne=x.multiplyUnsafe($)}catch{return!1}if(!U&&O.isSmallOrder())return!1;let be=H(M,Q.toRawBytes(),O.toRawBytes(),E);return Q.add(O.multiplyUnsafe(be)).subtract(ne).clearCofactor().equals(y.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:J,sign:V,verify:I,ExtendedPoint:y,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,E=y.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var Cc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Zf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),nv=BigInt(0),A0=BigInt(1),Xf=BigInt(2),sv=BigInt(3),S0=BigInt(5),_0=BigInt(8);function B0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Cc,a=r*r%o*r%o,c=ie(a,Xf,o)*a%o,u=ie(c,A0,o)*r%o,f=ie(u,S0,o)*u%o,l=ie(f,e,o)*f%o,d=ie(l,t,o)*l%o,h=ie(d,n,o)*d%o,p=ie(h,s,o)*h%o,m=ie(p,s,o)*h%o,g=ie(m,e,o)*f%o;return{pow_p_5_8:ie(g,Xf,o)*r%o,b2:a}}function C0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function I0(r,e){let t=Cc,n=ee(e*e*e,t),s=ee(n*n*e,t),o=B0(r*s).pow_p_5_8,i=ee(r*n*o,t),a=ee(e*i*i,t),c=i,u=ee(i*Zf,t),f=a===r,l=a===ee(-r,t),d=a===ee(-r*Zf,t);return f&&(i=c),(l||d)&&(i=u),Kf(i,t)&&(i=ee(-i,t)),{isValid:f||l,value:i}}var k0=Yt(Cc,void 0,!0),T0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:k0,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Uf,randomBytes:Qs,adjustScalarBytes:C0,uvRatio:I0},$n=jf(T0);var lo=32,uo=64,Ic=32;function Yf(){let r=$n.utils.randomPrivateKey(),e=$n.getPublicKey(r);return{privateKey:L0(r,e),publicKey:e}}function Jf(r,e){let t=r.subarray(0,Ic);return $n.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Qf(r,e,t){return $n.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function L0(r,e){let t=new Uint8Array(uo);for(let n=0;n<Ic;n++)t[n]=r[n],t[Ic+n]=e[n];return t}var zn=class{type="Ed25519";raw;constructor(e){this.raw=ho(e,lo)}toMultihash(){return _t.digest(pt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return Qf(this.raw,t,e)}},fo=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ho(e,uo),this.publicKey=new zn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return Jf(this.raw,e)}};function kc(r){return r=ho(r,lo),new zn(r)}async function th(){let{privateKey:r,publicKey:e}=Yf();return new fo(r,e)}function ho(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function fe(r=0){return new Uint8Array(r)}function Ce(r=0){return new Uint8Array(r)}var N0=Math.pow(2,7),P0=Math.pow(2,14),D0=Math.pow(2,21),Tc=Math.pow(2,28),Lc=Math.pow(2,35),Nc=Math.pow(2,42),Pc=Math.pow(2,49),Y=128,Ie=127;function pe(r){if(r<N0)return 1;if(r<P0)return 2;if(r<D0)return 3;if(r<Tc)return 4;if(r<Lc)return 5;if(r<Nc)return 6;if(r<Pc)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,e,t=0){switch(pe(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function R0(r,e,t=0){switch(pe(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Rc(r,e){let t=r[e],n=0;if(n+=t&Ie,t<Y||(t=r[e+1],n+=(t&Ie)<<7,t<Y)||(t=r[e+2],n+=(t&Ie)<<14,t<Y)||(t=r[e+3],n+=(t&Ie)<<21,t<Y)||(t=r[e+4],n+=(t&Ie)*Tc,t<Y)||(t=r[e+5],n+=(t&Ie)*Lc,t<Y)||(t=r[e+6],n+=(t&Ie)*Nc,t<Y)||(t=r[e+7],n+=(t&Ie)*Pc,t<Y))return n;throw new RangeError("Could not decode varint")}function M0(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<Y||(t=r.get(e+1),n+=(t&Ie)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ie)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ie)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ie)*Tc,t<Y)||(t=r.get(e+5),n+=(t&Ie)*Lc,t<Y)||(t=r.get(e+6),n+=(t&Ie)*Nc,t<Y)||(t=r.get(e+7),n+=(t&Ie)*Pc,t<Y))return n;throw new RangeError("Could not decode varint")}function ke(r,e,t=0){return e==null&&(e=Ce(pe(r))),e instanceof Uint8Array?Dc(r,e,t):R0(r,e,t)}function it(r,e=0){return r instanceof Uint8Array?Rc(r,e):M0(r,e)}var Mc=new Float32Array([-0]),Jt=new Uint8Array(Mc.buffer);function rh(r,e,t){Mc[0]=r,e[t]=Jt[0],e[t+1]=Jt[1],e[t+2]=Jt[2],e[t+3]=Jt[3]}function nh(r,e){return Jt[0]=r[e],Jt[1]=r[e+1],Jt[2]=r[e+2],Jt[3]=r[e+3],Mc[0]}var Uc=new Float64Array([-0]),Te=new Uint8Array(Uc.buffer);function sh(r,e,t){Uc[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 oh(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],Uc[0]}var U0=BigInt(Number.MAX_SAFE_INTEGER),O0=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 xr;if(e<U0&&e>O0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>ih&&(s=0n,++n>ih&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return xr;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}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):xr}},xr=new je(0,0);xr.toBigInt=function(){return 0n};xr.zzEncode=xr.zzDecode=function(){return this};xr.length=function(){return 1};var ih=4294967296n;function ah(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 ch(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Oc(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function at(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function po(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Fc=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 po(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw at(this,4);return po(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw at(this,4);let e=nh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw at(this,4);let e=oh(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 ch(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=po(this.buf,this.pos+=4),t=po(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=Rc(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 Vc(r){return new Fc(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=Vc(r);return e.decode(n,void 0,t)}var Hc={};Re(Hc,{base10:()=>F0});var F0=zt({prefix:"9",name:"base10",alphabet:"0123456789"});var Kc={};Re(Kc,{base16:()=>V0,base16upper:()=>H0});var V0=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),H0=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qc={};Re(qc,{base2:()=>K0});var K0=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $c={};Re($c,{base256emoji:()=>W0});var uh=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}"),q0=uh.reduce((r,e,t)=>(r[t]=e,r),[]),$0=uh.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function z0(r){return r.reduce((e,t)=>(e+=q0[t],e),"")}function G0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=$0[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var W0=Wr({prefix:"\u{1F680}",name:"base256emoji",encode:z0,decode:G0});var Wc={};Re(Wc,{base64:()=>zc,base64pad:()=>j0,base64url:()=>Gc,base64urlpad:()=>Z0});var zc=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),j0=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gc=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Z0=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jc={};Re(jc,{base8:()=>X0});var X0=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Zc={};Re(Zc,{identity:()=>Y0});var Y0=Wr({prefix:"\0",name:"identity",encode:r=>yf(r),decode:r=>gf(r)});var Uv=new TextEncoder,Ov=new TextDecoder;var Jc={};Re(Jc,{sha256:()=>rn,sha512:()=>ey});function Yc({name:r,code:e,encode:t}){return new Xc(r,e,t)}var Xc=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 hh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rn=Yc({name:"sha2-256",code:18,encode:hh("SHA-256")}),ey=Yc({name:"sha2-512",code:19,encode:hh("SHA-512")});var Gn={...Zc,...qc,...jc,...Hc,...Kc,...ic,...ac,...oc,...Wc,...$c},Xv={...Jc,...uc};function ph(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var dh=ph("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Qc=ph("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=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ty={utf8:dh,"utf-8":dh,hex:Gn.base16,latin1:Qc,ascii:Qc,binary:Qc,...Gn},mo=ty;function P(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function el(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ce(i);s+i>e&&(n=Ce(e),s=0);let a=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),a}}var vr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function tl(){}var nl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ry=el();function ny(r){return globalThis.Buffer!=null?Ce(r):ry(r)}var jn=class{len;head;tail;states;constructor(){this.len=0,this.head=new vr(tl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new vr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new sl((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(go,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(go,t.length(),t)}uint64Number(e){return this._push(Dc,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(go,t.length(),t)}sint64Number(e){let t=je.fromNumber(e).zzEncode();return this._push(go,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(rl,1,e?1:0)}fixed32(e){return this._push(Wn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=je.fromBigInt(e);return this._push(Wn,4,t.lo)._push(Wn,4,t.hi)}fixed64Number(e){let t=je.fromNumber(e);return this._push(Wn,4,t.lo)._push(Wn,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(rh,4,e)}double(e){return this._push(sh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(rl,1,0):this.uint32(t)._push(oy,t,e)}string(e){let t=ah(e);return t!==0?this.uint32(t)._push(Oc,t,e):this._push(rl,1,0)}fork(){return this.states=new nl(this),this.head=this.tail=new vr(tl,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 vr(tl,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=ny(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function rl(r,e,t){e[t]=r&255}function sy(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var sl=class extends vr{next;constructor(e,t){super(sy,e,t),this.next=void 0}};function go(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 Wn(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 oy(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(jn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(iy,e,r),this},jn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(ay,e,r),this});function iy(r,e,t){e.set(r,t)}function ay(r,e,t){r.length<40?Oc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function ol(){return new jn}function Ue(r,e){let t=ol();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var nn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(nn||(nn={}));function yo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function il(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return yo("enum",nn.VARINT,t,n)}function Oe(r,e){return yo("message",nn.LENGTH_DELIMITED,r,e)}var Er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Zn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ye;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ye||(ye={}));var al;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(al||(al={}));(function(r){r.codec=()=>il(al)})(ye||(ye={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ye.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ye.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(mt||(mt={}));var cl;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ye.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ye.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(cl||(cl={}));var is={};Re(is,{MAX_RSA_KEY_SIZE:()=>hi,generateRSAKeyPair:()=>El,jwkToJWKKeyPair:()=>gd,jwkToPkcs1:()=>By,jwkToPkix:()=>xl,jwkToRSAPrivateKey:()=>md,pkcs1ToJwk:()=>hd,pkcs1ToRSAPrivateKey:()=>pd,pkixToJwk:()=>dd,pkixToRSAPublicKey:()=>vl});function cy(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ll(r,...e){if(!cy(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ul(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 gh(r,e){ll(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var bo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ct=(r,e)=>r<<32-e|r>>>e;function ly(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function fl(r){return typeof r=="string"&&(r=ly(r)),ll(r),r}var wo=class{clone(){return this._cloneInto()}};function yh(r){let e=n=>r().update(fl(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function wh(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 uy(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(t>>s&o),a=Number(t&o),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var bh=(r,e,t)=>r&e^~r&t,xh=(r,e,t)=>r&e^r&t^e&t,xo=class extends wo{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=bo(this.buffer)}update(e){ul(this);let{view:t,buffer:n,blockLen:s}=this;e=fl(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=bo(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ul(this),gh(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let l=i;l<s;l++)t[l]=0;uy(n,s-8,BigInt(this.length*8),o),this.process(n,0);let a=bo(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],o)}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:s,finished:o,destroyed:i,pos:a}=this;return e.length=s,e.pos=a,e.finished=o,e.destroyed=i,s%t&&e.buffer.set(n),e}};var fy=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]),Qt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),er=new Uint32Array(64),hl=class extends xo{constructor(){super(64,32,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|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)er[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=er[l-15],h=er[l-2],p=ct(d,7)^ct(d,18)^d>>>3,m=ct(h,17)^ct(h,19)^h>>>10;er[l]=m+er[l-7]+p+er[l-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=ct(a,6)^ct(a,11)^ct(a,25),h=f+d+bh(a,c,u)+fy[l]+er[l]|0,m=(ct(n,2)^ct(n,13)^ct(n,22))+xh(n,s,o)|0;f=u,u=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+m|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,u,f)}roundClean(){er.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vo=yh(()=>new hl);var q=hr(vh());function Sr(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 tr(r,e,t=-1){let n=t,s=r,o=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),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[o-f-1]=Math.floor(s/l),s-=u[o-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function So(...r){let e=0,t=0;for(let o of r)e+=o.length;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let o of r)s.set(o,t),t+=o.length;return s}function pl(){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=Sr(t,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=r[a];return o[0]&=127,Sr(o,8)-n}function Eh(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=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=tr(e,8,n),o=new Uint8Array(s);if(o[0]&128){let i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ah(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}function ze(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(t)}var F2=Math.log(2);function _o(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ml(r){let e=0,t=0;for(let s=0;s<r.length;s++){let o=r[s];e+=o.byteLength}let n=new Uint8Array(e);for(let s=0;s<r.length;s++){let o=r[s];n.set(new Uint8Array(o),t),t+=o.byteLength}return n.buffer}function Dt(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 Yn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ml(this.items)}},Xn=[new Uint8Array([1])],Sh="0123456789";var ln="",lt=new ArrayBuffer(0),gl=new Uint8Array(0),Jn="EndOfContent",Bh="OCTET STRING",Ch="BIT STRING";function Rt(r){var e;return e=class extends r{constructor(...n){var s;super(...n);let o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?q.BufferSourceConverter.toUint8Array(o.valueHex):gl}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,s,o){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Dt(this,i,s,o))return-1;let a=s+o;return this.valueHexView=i.subarray(s,a),this.valueHexView.length?(this.blockLength=o,a):(this.warnings.push("Zero buffer length"),s)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",lt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=ln,warnings:n=[],valueBeforeDecode:s=gl}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(s)}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)}}};Lt.NAME="baseBlock";var Le=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Le.NAME="valueBlock";var Bo=class extends Rt(Lt){constructor({idBlock:e={}}={}){var t,n,s,o;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):gl,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",lt}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,t|=o,s[0]=t}return s.buffer}if(!this.isHexOnly){let s=tr(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,t,n){let s=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[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=(o[0]&32)===32,this.isHexOnly=!1;let a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;o[c]&128;){if(u[c-1]=o[c]&127,c++,c>=o.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]=o[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=Sr(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}}};Bo.NAME="identificationBlock";var Co=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,s;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=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,t,n){let s=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Sr(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 s=tr(this.length,8);if(s.byteLength>127)return this.error="Too big length",lt;if(t=new ArrayBuffer(s.byteLength+1),e)return t;let o=new Uint8Array(s);n=new Uint8Array(t),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[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}}};Co.NAME="lengthBlock";var T={},Ae=class extends Lt{constructor({name:e=ln,optional:t=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Bo(s),this.lenBlock=new Co(s),this.valueBlock=o?new o(s):new Le(s)}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(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),s)}toBER(e,t){let n=t||new Yn;t||Ih(this);let s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return t?lt:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():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 Ah(t,n)}};Ae.NAME="BaseBlock";function Ih(r){if(r instanceof T.Constructed)for(let e of r.valueBlock.value)Ih(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Io=class extends Ae{constructor({value:e=ln,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(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),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Io.NAME="BaseStringBlock";var ko=class extends Rt(Le){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};ko.NAME="PrimitiveValueBlock";var kh,To=class extends Ae{constructor(e={}){super(e,ko),this.idBlock.isConstructed=!1}};kh=To;T.Primitive=kh;To.NAME="PRIMITIVE";function xy(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 ui(r,e=0,t=r.length){let n=e,s=new Ae({},Le),o=new Lt;if(!Dt(o,r,e,t))return s.error=o.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let a=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),a===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=a,t-=s.idBlock.blockLength,a=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),a===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};if(e=a,t-=s.lenBlock.blockLength,!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let c=Ae;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};c=T.EndOfContent;break;case 1:c=T.Boolean;break;case 2:c=T.Integer;break;case 3:c=T.BitString;break;case 4:c=T.OctetString;break;case 5:c=T.Null;break;case 6:c=T.ObjectIdentifier;break;case 10:c=T.Enumerated;break;case 12:c=T.Utf8String;break;case 13:c=T.RelativeObjectIdentifier;break;case 14:c=T.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:c=T.Sequence;break;case 17:c=T.Set;break;case 18:c=T.NumericString;break;case 19:c=T.PrintableString;break;case 20:c=T.TeletexString;break;case 21:c=T.VideotexString;break;case 22:c=T.IA5String;break;case 23:c=T.UTCTime;break;case 24:c=T.GeneralizedTime;break;case 25:c=T.GraphicString;break;case 26:c=T.VisibleString;break;case 27:c=T.GeneralString;break;case 28:c=T.UniversalString;break;case 29:c=T.CharacterString;break;case 30:c=T.BmpString;break;case 31:c=T.DATE;break;case 32:c=T.TimeOfDay;break;case 33:c=T.DateTime;break;case 34:c=T.Duration;break;default:{let u=s.idBlock.isConstructed?new T.Constructed:new T.Primitive;u.idBlock=s.idBlock,u.lenBlock=s.lenBlock,u.warnings=s.warnings,s=u}}break;case 2:case 3:case 4:default:c=s.idBlock.isConstructed?T.Constructed:T.Primitive}return s=xy(s,c),a=s.fromBER(r,e,s.lenBlock.isIndefiniteForm?t:s.lenBlock.length),s.valueBeforeDecodeView=r.subarray(n,n+s.blockLength),{offset:a,result:s}}function yl(r){if(!r.byteLength){let e=new Ae({},Le);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ui(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function vy(r,e){return r?1:e}var gt=class extends Le{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let s=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let o=t;for(;vy(this.isIndefiniteForm,n)>0;){let i=ui(s,o,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(o=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Jn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Jn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){let n=t||new Yn;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return t?lt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};gt.NAME="ConstructedValueBlock";var Th,rr=class extends Ae{constructor(e={}){super(e,gt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(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),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
3
|
+
`).map(s=>` ${s}`).join(`
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
6
|
-
`)}`:`${t} :`}};Sh=tr;T.Constructed=Sh;tr.NAME="CONSTRUCTED";var Is=class extends Le{fromBER(e,t,n){return t}toBER(e){return lt}};Is.override="EndOfContentValueBlock";var _h,ks=class extends Ae{constructor(e={}){super(e,Is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_h=ks;T.EndOfContent=_h;ks.NAME=Xn;var Bh,on=class extends Ae{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}`}};Bh=on;T.Null=Bh;on.NAME="NULL";var Ts=class extends Dt(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 Pt(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,ul.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="BooleanValueBlock";var Ch,Ls=class extends Ae{constructor(e={}){super(e,Ts),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}`}};Ch=Ls;T.Boolean=Ch;Ls.NAME="BOOLEAN";var Ns=class extends Dt(mt){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=mt.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===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==xh)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?mt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Ns.NAME="OctetStringValueBlock";var Ih,Ps=class r extends Ae{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},Ns),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=ai(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?tr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${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)}};Ih=Ps;T.OctetString=Ih;Ps.NAME=xh;var Ds=class extends Dt(mt){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=mt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==vh)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(!Pt(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=ai(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 mt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ds.NAME="BitStringValueBlock";var kh,sn=class extends Ae{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},Ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return tr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};kh=sn;T.BitString=kh;sn.NAME=vh;var Th;function hy(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=vs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=vs(t,s)),s}function bh(r){if(r>=jn.length)for(let e=jn.length;e<=r;e++){let t=new Uint8Array([0]),n=jn[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=vs(t,n)),jn.push(n)}return jn[r]}function dy(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 Yn=class extends Dt(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=ul.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gh(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=dy(bh(n),t),i="-";break;default:t=hy(t,bh(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=wh.charAt(t[c]));return a===!1&&(i+=wh.charAt(0)),i}};Th=Yn;Yn.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 Lh,Se=class r extends Ae{constructor(e={}){super(e,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Es(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Es();let t=BigInt(e),n=new Zn,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()}`}};Lh=Se;T.Integer=Lh;Se.NAME="INTEGER";var Nh,Rs=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Nh=Rs;T.Enumerated=Nh;Rs.NAME="ENUMERATED";var Jn=class extends Dt(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(!Pt(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=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Es();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=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}}};Jn.NAME="sidBlock";var Ms=class extends Le{constructor({value:e=cn,...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.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,lt;t.push(o)}return fl(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 Jn;if(o>Number.MAX_SAFE_INTEGER){Es();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}};Ms.NAME="ObjectIdentifierValueBlock";var Ph,an=class extends Ae{constructor(e={}){super(e,Ms),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()}}};Ph=an;T.ObjectIdentifier=Ph;an.NAME="OBJECT IDENTIFIER";var Qn=class extends Dt(Tt){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(!Pt(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=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=er(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Qn.NAME="relativeSidBlock";var Us=class extends Le{constructor({value:e=cn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Qn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,lt;n.push(s)}return fl(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 Qn;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}};Us.NAME="RelativeObjectIdentifierValueBlock";var Dh,Os=class extends Ae{constructor(e={}){super(e,Us),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()}}};Dh=Os;T.RelativeObjectIdentifier=Dh;Os.NAME="RelativeObjectIdentifier";var Rh,Lt=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Rh=Lt;T.Sequence=Rh;Lt.NAME="SEQUENCE";var Mh,Fs=class extends tr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Mh=Fs;T.Set=Mh;Fs.NAME="SET";var Vs=class extends Dt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=cn}toJSON(){return{...super.toJSON(),value:this.value}}};Vs.NAME="StringValueBlock";var Hs=class extends Vs{};Hs.NAME="SimpleStringValueBlock";var Fe=class extends _s{constructor({...e}={}){super(e,Hs)}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}};Fe.NAME="SIMPLE STRING";var Ks=class extends Fe{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}};Ks.NAME="Utf8StringValueBlock";var Uh,Nt=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Uh=Nt;T.Utf8String=Uh;Nt.NAME="UTF8String";var qs=class extends Fe{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))}};qs.NAME="BmpStringValueBlock";var Oh,$s=class extends qs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Oh=$s;T.BmpString=Oh;$s.NAME="BMPString";var zs=class extends Fe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=er(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};zs.NAME="UniversalStringValueBlock";var Fh,Gs=class extends zs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Fh=Gs;T.UniversalString=Fh;Gs.NAME="UniversalString";var Vh,Ws=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Vh=Ws;T.NumericString=Vh;Ws.NAME="NumericString";var Hh,js=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Hh=js;T.PrintableString=Hh;js.NAME="PrintableString";var Kh,Zs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Kh=Zs;T.TeletexString=Kh;Zs.NAME="TeletexString";var qh,Xs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};qh=Xs;T.VideotexString=qh;Xs.NAME="VideotexString";var $h,Ys=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};$h=Ys;T.IA5String=$h;Ys.NAME="IA5String";var zh,Js=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};zh=Js;T.GraphicString=zh;Js.NAME="GraphicString";var Gh,eo=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gh=eo;T.VisibleString=Gh;eo.NAME="VisibleString";var Wh,Qs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Wh=Qs;T.GeneralString=Wh;Qs.NAME="GeneralString";var jh,ei=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};jh=ei;T.CharacterString=jh;ei.NAME="CharacterString";var Zh,to=class extends eo{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]=ze(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ze(this.month,2),t[2]=ze(this.day,2),t[3]=ze(this.hour,2),t[4]=ze(this.minute,2),t[5]=ze(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}}};Zh=to;T.UTCTime=Zh;to.NAME="UTCTime";var Xh,ti=class extends to{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(ze(this.year,4)),t.push(ze(this.month,2)),t.push(ze(this.day,2)),t.push(ze(this.hour,2)),t.push(ze(this.minute,2)),t.push(ze(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ze(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Xh=ti;T.GeneralizedTime=Xh;ti.NAME="GeneralizedTime";var Yh,ri=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Yh=ri;T.DATE=Yh;ri.NAME="DATE";var Jh,ni=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Jh=ni;T.TimeOfDay=Jh;ni.NAME="TimeOfDay";var Qh,oi=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Qh=oi;T.DateTime=Qh;oi.NAME="DateTime";var ed,si=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};ed=si;T.Duration=ed;si.NAME="Duration";var td,ii=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};td=ii;T.TIME=td;ii.NAME="TIME";function te(r,e="utf8"){let t=hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function ln(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return hh(r)}var ro=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},no=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ci=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var rd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ci("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 rr=rd;async function nd(r){let e=await rr.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 my(e);return{privateKey:t[0],publicKey:t[1]}}async function od(r,e){let t=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await rr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function sd(r,e,t){let n=await rr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return rr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function my(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([rr.get().subtle.exportKey("jwk",r.privateKey),rr.get().subtle.exportKey("jwk",r.publicKey)])}function pl(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return P(r.n,"base64url").length*8}var un=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return me.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return sd(this._key,t,e)}},so=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return od(this._key,e)}};var li=8192,ml=18;function id(r){let{result:e}=dl(r),t=e.valueBlock.value;return{n:gt(t[1]),e:gt(t[2]),d:gt(t[3]),p:gt(t[4]),q:gt(t[5]),dp:gt(t[6]),dq:gt(t[7]),qi:gt(t[8]),kty:"RSA",alg:"RS256"}}function gy(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 R("JWK was missing components");let t=new Lt({value:[new Se({value:0}),Se.fromBigInt(yt(P(r.n,"base64url"))),Se.fromBigInt(yt(P(r.e,"base64url"))),Se.fromBigInt(yt(P(r.d,"base64url"))),Se.fromBigInt(yt(P(r.p,"base64url"))),Se.fromBigInt(yt(P(r.q,"base64url"))),Se.fromBigInt(yt(P(r.dp,"base64url"))),Se.fromBigInt(yt(P(r.dq,"base64url"))),Se.fromBigInt(yt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function ad(r){let{result:e}=dl(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:gt(t[0]),e:gt(t[1])}}function gl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");let t=new Lt({value:[new Lt({value:[new an({value:"1.2.840.113549.1.1.1"}),new on]}),new sn({valueHex:new Lt({value:[Se.fromBigInt(yt(P(r.n,"base64url"))),Se.fromBigInt(yt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function gt(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return te(e,"base64url")}function yt(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 cd(r){let e=id(r);return ld(e)}function yl(r){let e=ad(r);if(pl(e)>li)throw new Hr("Key size is too large");let t=ws(pt.encode({Type:ye.RSA,Data:r})),n=tt(ml,t);return new un(e,n)}function ld(r){if(pl(r)>li)throw new R("Key size is too large");let e=ud(r),t=ws(pt.encode({Type:ye.RSA,Data:gl(e.publicKey)})),n=tt(ml,t);return new so(e.privateKey,new un(e.publicKey,n))}async function wl(r){if(r>li)throw new R("Key size is too large");let e=await nd(r),t=ws(pt.encode({Type:ye.RSA,Data:gl(e.publicKey)})),n=tt(ml,t);return new so(e.privateKey,new un(e.publicKey,n))}function ud(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var yy=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]),nr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),bl=class extends Qr{constructor(){super(64,32,8,!1),this.A=nr[0]|0,this.B=nr[1]|0,this.C=nr[2]|0,this.D=nr[3]|0,this.E=nr[4]|0,this.F=nr[5]|0,this.G=nr[6]|0,this.H=nr[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)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=or[l-15],h=or[l-2],p=nt(d,7)^nt(d,18)^d>>>3,m=nt(h,17)^nt(h,19)^h>>>10;or[l]=m+or[l-7]+p+or[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+If(a,c,u)+yy[l]+or[l]|0,m=(nt(n,2)^nt(n,13)^nt(n,22))+kf(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(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var fd=Xo(()=>new bl);var ui=class extends Jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,_f(e);let n=On(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Xr(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()}},xl=(r,e,t)=>new ui(r,e).update(t).digest();xl.create=(r,e)=>new ui(r,e);function hd(r){r.lowS!==void 0&&ot("lowS",r.lowS),r.prehash!==void 0&&ot("prehash",r.prehash)}function wy(r){let e=Hn(r);ht(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:by,hexToBytes:xy}=ts,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=pr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?pr(o.length/2|128):"";return pr(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<Mt)throw new e("integer: negative integers are not allowed");let t=pr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");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 by(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Rt,o=typeof r=="string"?xy(r):r;en(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)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Mt=BigInt(0),ve=BigInt(1),uE=BigInt(2),dd=BigInt(3),fE=BigInt(4);function vy(r){let e=wy(r),{Fp:t}=e,n=Xt(e.n,e.nBitLength),o=e.toBytes||((m,g,w)=>{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),w=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:w,y:b}});function i(m){let{a:g,b:w}=e,b=t.sqr(m),y=t.mul(b,m);return t.add(t.add(y,t.mul(m,g)),w)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Fn(m,ve,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:b,n:y}=e;if(g&&typeof m!="bigint"){if(Wt(m)&&(m=Bt(m)),typeof m!="string"||!g.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let x;try{x=typeof m=="bigint"?m:Ct(ae("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return b&&(x=Q(x,y)),qe("private key",x,ve,y),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=yr((m,g)=>{let{px:w,py:b,pz:y}=m;if(t.eql(y,t.ONE))return{x:w,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(y));let A=t.mul(w,g),_=t.mul(b,g),v=t.mul(y,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=yr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=m.toAffine();if(!t.isValid(g)||!t.isValid(w))throw new Error("bad point: x or y not FE");let b=t.sqr(w),y=i(g);if(!t.eql(b,y))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,w,b){if(this.px=g,this.py=w,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:w,y:b}=g||{};if(!g||!t.isValid(w)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let y=x=>t.eql(x,t.ZERO);return y(w)&&y(b)?d.ZERO:new d(w,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let w=t.invertBatch(g.map(b=>b.pz));return g.map((b,y)=>b.toAffine(w[y])).map(d.fromAffine)}static fromHex(g){let w=d.fromAffine(s(ae("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return ss(d,n,g,w)}_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:w,py:b,pz:y}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(w,_),t.mul(x,y)),B=t.eql(t.mul(b,_),t.mul(A,y));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:w}=e,b=t.mul(w,dd),{px:y,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,k=t.mul(y,y),Y=t.mul(x,x),H=t.mul(A,A),V=t.mul(y,x);return V=t.add(V,V),B=t.mul(y,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,H),v=t.add(_,v),_=t.sub(Y,v),v=t.add(Y,v),v=t.mul(_,v),_=t.mul(V,_),B=t.mul(b,B),H=t.mul(g,H),V=t.sub(k,H),V=t.mul(g,V),V=t.add(V,B),B=t.add(k,k),k=t.add(B,k),k=t.add(k,H),k=t.mul(k,V),v=t.add(v,k),H=t.mul(x,A),H=t.add(H,H),k=t.mul(H,V),_=t.sub(_,k),B=t.mul(H,Y),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:w,py:b,pz:y}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,k=t.ZERO,Y=e.a,H=t.mul(e.b,dd),V=t.mul(w,x),D=t.mul(b,A),I=t.mul(y,_),N=t.add(w,b),S=t.add(x,A);N=t.mul(N,S),S=t.add(V,D),N=t.sub(N,S),S=t.add(w,y);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(V,I),S=t.sub(S,E),E=t.add(b,y),v=t.add(A,_),E=t.mul(E,v),v=t.add(D,I),E=t.sub(E,v),k=t.mul(Y,S),v=t.mul(H,I),k=t.add(v,k),v=t.sub(D,k),k=t.add(D,k),B=t.mul(v,k),D=t.add(V,V),D=t.add(D,V),I=t.mul(Y,I),S=t.mul(H,S),D=t.add(D,I),I=t.sub(V,I),I=t.mul(Y,I),S=t.add(S,I),V=t.mul(D,S),B=t.add(B,V),V=t.mul(E,S),v=t.mul(N,v),v=t.sub(v,V),V=t.mul(N,D),k=t.mul(E,k),k=t.add(k,V),new d(v,B,k)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){let{endo:w,n:b}=e;qe("scalar",g,Mt,b);let y=d.ZERO;if(g===Mt)return y;if(this.is0()||g===ve)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:x,k1:A,k2neg:_,k2:v}=w.splitScalar(g),B=y,k=y,Y=this;for(;A>Mt||v>Mt;)A&ve&&(B=B.add(Y)),v&ve&&(k=k.add(Y)),Y=Y.double(),A>>=ve,v>>=ve;return x&&(B=B.negate()),_&&(k=k.negate()),k=new d(t.mul(k.px,w.beta),k.py,k.pz),B.add(k)}multiply(g){let{endo:w,n:b}=e;qe("scalar",g,ve,b);let y,x;if(w){let{k1neg:A,k1:_,k2neg:v,k2:B}=w.splitScalar(g),{p:k,f:Y}=this.wNAF(_),{p:H,f:V}=this.wNAF(B);k=p.constTimeNegate(A,k),H=p.constTimeNegate(v,H),H=new d(t.mul(H.px,w.beta),H.py,H.pz),y=k.add(H),x=Y.add(V)}else{let{p:A,f:_}=this.wNAF(g);y=A,x=_}return d.normalizeZ([y,x])[0]}multiplyAndAddUnsafe(g,w,b){let y=d.BASE,x=(_,v)=>v===Mt||v===ve||!_.equals(y)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,w).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:w}=e;if(g===ve)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:w}=e;return g===ve?this:w?w(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),Bt(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=os(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Ey(r){let e=Hn(r);return ht(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function pd(r){let e=Ey(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Q(I,n)}function a(I){return rs(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=vy({...e,toBytes(I,N,S){let E=N.toAffine(),C=t.toBytes(E.x),L=It;return ot("isCompressed",S),S?L(Uint8Array.from([N.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,t.toBytes(E.y))},fromBytes(I){let N=I.length,S=I[0],E=I.subarray(1);if(N===o&&(S===2||S===3)){let C=Ct(E);if(!Fn(C,ve,t.ORDER))throw new Error("Point is not on curve");let L=f(C),M;try{M=t.sqrt(L)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let U=(M&ve)===ve;return(S&1)===1!==U&&(M=t.neg(M)),{x:C,y:M}}else if(N===s&&S===4){let C=t.fromBytes(E.subarray(0,t.BYTES)),L=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:C,y:L}}else{let C=o,L=s;throw new Error("invalid Point, expected length of "+C+", or uncompressed "+L+", got "+N)}}}),d=I=>Bt(Zt(I,e.nByteLength));function h(I){let N=n>>ve;return I>N}function p(I){return h(I)?i(-I):I}let m=(I,N,S)=>Ct(I.slice(N,S));class g{constructor(N,S,E){this.r=N,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(N){let S=e.nByteLength;return N=ae("compactSignature",N,S*2),new g(m(N,0,S),m(N,S,2*S))}static fromDER(N){let{r:S,s:E}=Rt.toSig(ae("DER",N));return new g(S,E)}assertValidity(){qe("r",this.r,ve,n),qe("s",this.s,ve,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:S,s:E,recovery:C}=this,L=_(ae("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let M=C===2||C===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=C&1?"03":"02",K=c.fromHex(U+d(M)),$=a(M),O=i(-L*$),J=i(E*$),ne=c.BASE.multiplyAndAddUnsafe(K,O,J);if(!ne)throw new Error("point at infinify");return ne.assertValidity(),ne}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return mr(this.toDERHex())}toDERHex(){return Rt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return mr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let I=wc(e.n);return Of(e.randomBytes(I),e.n)},precompute(I=8,N=c.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function b(I,N=!0){return c.fromPrivateKey(I).toRawBytes(N)}function y(I){let N=Wt(I),S=typeof I=="string",E=(N||S)&&I.length;return N?E===o||E===s:S?E===2*o||E===2*s:I instanceof c}function x(I,N,S=!0){if(y(I))throw new Error("first arg must be private key");if(!y(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(u(I)).toRawBytes(S)}let A=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=Ct(I),S=I.length*8-e.nBitLength;return S>0?N>>BigInt(S):N},_=e.bits2int_modN||function(I){return i(A(I))},v=Vn(e.nBitLength);function B(I){return qe("num < 2^"+e.nBitLength,I,Mt,v),Zt(I,e.nByteLength)}function k(I,N,S=Y){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:C}=e,{lowS:L,prehash:M,extraEntropy:U}=S;L==null&&(L=!0),I=ae("msgHash",I),hd(S),M&&(I=ae("prehashed msgHash",E(I)));let K=_(I),$=u(N),O=[B($),B(K)];if(U!=null&&U!==!1){let xe=U===!0?C(t.BYTES):U;O.push(ae("extraEntropy",xe))}let J=It(...O),ne=K;function be(xe){let Ee=A(xe);if(!l(Ee))return;let Be=a(Ee),Ke=c.BASE.multiply(Ee).toAffine(),De=i(Ke.x);if(De===Mt)return;let ft=i(Be*i(ne+De*$));if(ft===Mt)return;let bt=(Ke.x===De?0:2)|Number(Ke.y&ve),Tn=ft;return L&&h(ft)&&(Tn=p(ft),bt^=1),new g(De,Tn,bt)}return{seed:J,k2sig:be}}let Y={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function V(I,N,S=Y){let{seed:E,k2sig:C}=k(I,N,S),L=e;return pc(L.hash.outputLen,L.nByteLength,L.hmac)(E,C)}c.BASE._setWindowSize(8);function D(I,N,S,E=H){let C=I;N=ae("msgHash",N),S=ae("publicKey",S);let{lowS:L,prehash:M,format:U}=E;if(hd(E),"strict"in E)throw new Error("options.strict was renamed to lowS");if(U!==void 0&&U!=="compact"&&U!=="der")throw new Error("format must be compact or der");let K=typeof C=="string"||Wt(C),$=!K&&!U&&typeof C=="object"&&C!==null&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!K&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,J;try{if($&&(O=new g(C.r,C.s)),K){try{U!=="compact"&&(O=g.fromDER(C))}catch(bt){if(!(bt instanceof Rt.Err))throw bt}!O&&U!=="der"&&(O=g.fromCompact(C))}J=c.fromHex(S)}catch{return!1}if(!O||L&&O.hasHighS())return!1;M&&(N=e.hash(N));let{r:ne,s:be}=O,xe=_(N),Ee=a(be),Be=i(xe*Ee),Ke=i(ne*Ee),De=c.BASE.multiplyAndAddUnsafe(J,Be,Ke)?.toAffine();return De?i(De.x)===ne:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:V,verify:D,ProjectivePoint:c,Signature:g,utils:w}}function Ay(r){return{hash:r,hmac:(e,...t)=>xl(r,e,ac(...t)),randomBytes:Yo}}function md(r,e){let t=n=>pd({...r,...Ay(n)});return Object.freeze({...t(e),create:t})}var wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),gd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Sy=BigInt(1),vl=BigInt(2),yd=(r,e)=>(r+e/vl)/e;function _y(r){let e=wd,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=ie(f,t,e)*f%e,d=ie(l,t,e)*f%e,h=ie(d,vl,e)*u%e,p=ie(h,o,e)*h%e,m=ie(p,s,e)*p%e,g=ie(m,a,e)*m%e,w=ie(g,c,e)*g%e,b=ie(w,a,e)*m%e,y=ie(b,t,e)*f%e,x=ie(y,i,e)*p%e,A=ie(x,n,e)*u%e,_=ie(A,vl,e);if(!El.eql(El.sqr(_),r))throw new Error("Cannot find square root");return _}var El=Xt(wd,void 0,void 0,{sqrt:_y}),Ye=md({a:BigInt(0),b:BigInt(7),Fp:El,n:gd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=gd,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Sy*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=yd(s*r,e),c=yd(-n*r,e),u=Q(r-a*t-c*o,e),f=Q(-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}}}},fd),xE=BigInt(0);var vE=Ye.ProjectivePoint;function Ve(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ce(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Al(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function bd(r,e){let t=tn.digest(e instanceof Uint8Array?e:e.subarray());if(Al(t))return t.then(({digest:n})=>Ye.sign(n,r).toDERRawBytes()).catch(n=>{throw new ro(String(n))});try{return Ye.sign(t.digest,r).toDERRawBytes()}catch(n){throw new ro(String(n))}}function xd(r,e,t){let n=tn.digest(t instanceof Uint8Array?t:t.subarray());if(Al(n))return n.then(({digest:o})=>Ye.verify(e,o,r)).catch(o=>{throw new no(String(o))});try{return Ye.verify(e,n.digest,r)}catch(o){throw new no(String(o))}}var io=class{type="secp256k1";raw;_key;constructor(e){this._key=Ad(e),this.raw=vd(this._key)}toMultihash(){return St.digest(dt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return xd(this._key,t,e)}},fi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Ed(e),this.publicKey=new io(t??Sd(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return bd(this.raw,e)}};function Sl(r){return new io(r)}async function _d(){let r=By();return new fi(r)}function vd(r){return Ye.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ed(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new Ln(String(e))}}function Ad(r){try{return Ye.ProjectivePoint.fromHex(r),r}catch(e){throw new Hr(String(e))}}function Sd(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new Ln(String(e))}}function By(){return Ye.utils.randomPrivateKey()}async function Bd(r,e){if(r==="Ed25519")return Zf();if(r==="secp256k1")return _d();if(r==="RSA")return wl(e??2048);throw new qt}function fn(r){let{Type:e,Data:t}=pt.decode(r),n=t??new Uint8Array;switch(e){case ye.RSA:return yl(n);case ye.Ed25519:return _c(n);case ye.secp256k1:return Sl(n);default:throw new qt}}function Cd(r){let{Type:e,Data:t}=pt.decode(r.digest),n=t??new Uint8Array;switch(e){case ye.Ed25519:return _c(n);case ye.secp256k1:return Sl(n);default:throw new qt}}function dt(r){return pt.encode({Type:ye[r.type],Data:r.raw})}var Id=Symbol.for("nodejs.util.inspect.custom"),Cy=114,ao=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()})`}[Uo]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return me.createV1(Cy,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ue(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ue(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Id](){return`PeerId(${this.toString()})`}},co=class extends ao{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},lo=class extends ao{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},uo=class extends ao{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Iy=2336,fo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=St.digest(P(this.url))}[Id](){return`PeerId(${this.url})`}[Uo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return me.createV1(Iy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}};var ky=114,kd=2336;function wt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=rt(Z.decode(`z${r}`));else{if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=rt(e.decode(r))}return hn(t)}function _l(r){if(r.type==="Ed25519")return new lo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new uo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new co({multihash:r.toCID().multihash,publicKey:r});throw new qt}function Td(r){return _l(r.publicKey)}function hn(r){if(Ly(r))return new co({multihash:r});if(Ty(r))try{let e=Cd(r);if(e.type==="Ed25519")return new lo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new uo({multihash:r,publicKey:e})}catch{let t=te(r.digest);return new fo(new URL(t))}throw new Ko("Supplied PeerID Multihash is invalid")}function hi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ky&&r.code!==kd)throw new Ho("Supplied PeerID CID is invalid");if(r.code===kd){let e=te(r.multihash.digest);return new fo(new URL(e))}return hn(r.multihash)}function Ty(r){return r.code===St.code}function Ly(r){return r.code===tn.code}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Cl=hr(Nd(),1);var po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Pd=r=>globalThis.DOMException===void 0?new Il(r):new DOMException(r),Dd=r=>{let e=r.reason===void 0?Pd("This operation was aborted."):r.reason;return e instanceof Error?e:Pd(e)};function mo(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(Dd(d));let h=()=>{f(Dd(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new po;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 kl(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 go=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=kl(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 sr=class extends Cl.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:go,...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=mo(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 po&&!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 pi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Tl=60;function mi(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??Tl,data:e.data instanceof Uint8Array?te(e.data):e.data}))}}var Dy=4;function Ll(r,e={}){let t=new sr({concurrency:e.queryConcurrency??Dy});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(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=mi(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 Rd(){return[Ll("https://cloudflare-dns.com/dns-query"),Ll("https://dns.google/resolve")]}var Od=hr(Ud(),1);var Nl=class{lru;constructor(e){this.lru=(0,Od.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 mi({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??Tl)*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 Fd(r){return new Nl(r)}var Ry=1e3,gi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Fd(e.cacheSize??Ry),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["."]=Rd())}async query(e,t={}){let n=pi(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 Vd(r={}){return new gi(r)}var yi=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 Hd=45,My=15,dn=new yi;function Pl(r){if(!(r.length>My))return dn.new(r).parseWith(()=>dn.readIPv4Addr())}function Dl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hd))return dn.new(r).parseWith(()=>dn.readIPv6Addr())}function wi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hd))return dn.new(r).parseWith(()=>dn.readIPAddr())}var lS=parseInt("0xFFFF",16),uS=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ir(r){return!!Pl(r)}function pn(r){return!!Dl(r)}function bi(r){return!!wi(r)}var $d=ir,Hy=pn,Rl=function(r){let e=0;if(r=r.toString().trim(),$d(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Hy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=$d(t[n]),i;s&&(i=Rl(t[n]),t[n]=te(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,te(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")},zd=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 mn={},Ml={},qy=[[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"]];qy.forEach(r=>{let e=$y(...r);Ml[e.code]=e,mn[e.name]=e});function $y(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Ml[r]!=null)return Ml[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(mn[r]!=null)return mn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var WS=W("ip4"),jS=W("ip6"),ZS=W("ipcidr");function Vl(r,e){switch(W(r).code){case 4:case 41:return Gy(e);case 42:return Fl(e);case 6:case 273:case 33:case 132:return jd(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fl(e);case 421:return Xy(e);case 444:return Wd(e);case 445:return Wd(e);case 466:return Zy(e);case 481:return globalThis.encodeURIComponent(Fl(e));default:return te(e,"base16")}}function Hl(r,e){switch(W(r).code){case 4:return Gd(e);case 41:return Gd(e);case 42:return Ol(e);case 6:case 273:case 33:case 132:return Kl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ol(e);case 421:return Wy(e);case 444:return Yy(e);case 445:return Jy(e);case 466:return jy(e);case 481:return Ol(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var Ul=Object.values($n).map(r=>r.decoder),zy=function(){let r=Ul[0].or(Ul[1]);return Ul.slice(2).forEach(e=>r=r.or(e)),r}();function Gd(r){if(!bi(r))throw new Error("invalid ip address");return Rl(r)}function Gy(r){let e=zd(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!bi(e))throw new Error("invalid ip address");return e}function Kl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function jd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ol(r){let e=P(r),t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function Fl(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return te(r)}function Wy(r){let e;r[0]==="Q"||r[0]==="1"?e=rt(Z.decode(`z${r}`)).bytes:e=me.parse(r).multihash.bytes;let t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function jy(r){let e=zy.decode(r),t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function Zy(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+te(t,"base64url")}function Xy(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return te(t,"base58btc")}function Yy(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=Kl(n);return Ve([t,o],t.length+o.length)}function Jy(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=Kl(n);return Ve([t,o],t.length+o.length)}function Wd(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=te(e,"base32"),o=jd(t);return`${n}:${o}`}function Zd(r){r=ql(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Yd("invalid address: "+r);if(a.path===!0){n=ql(o.slice(s).join("/")),e.push([a.code,Hl(a.code,n)]),t.push([a.code,n]);break}let c=Hl(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Vl(a.code,c)])}return{string:Xd(t),bytes:zl(e),tuples:e,stringTuples:t,path:n}}function $l(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=pe(s),a=W(s),c=Qy(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 Yd("Invalid address Uint8Array: "+te(r,"base16"));e.push([s,u]);let f=Vl(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Xd(t),tuples:e,stringTuples:t,path:n}}function Xd(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),ql(e.join("/"))}function zl(r){return Ve(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(ke(t.code));return e.length>1&&e[1]!=null&&(n=Ve([n,e[1]])),n}))}function Qy(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 ql(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Yd(r){return new Error("Error parsing address: "+r)}var ew=Symbol.for("nodejs.util.inspect.custom"),Wl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),tw=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Gl=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},xi=class r{bytes;#e;#t;#s;#a;[Wl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=$l(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Zd(e)}else if(ar(e))t=$l(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),tw.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=W(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({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#s.map(([e,t])=>t==null?[e]:[e,t])}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(zl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===mn.p2p.code&&e.push([n,o]),n===mn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?te(Z.decode(`z${n}`),"base58btc"):te(me.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ue(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=gn.get(t.name);if(n==null)throw new Gl(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>re(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)}[ew](){return`Multiaddr(${this.#e})`}};var gn=new Map;function ar(r){return!!r?.[Wl]}function re(r){return new xi(r)}var rw=32,{code:nw}=W("dnsaddr"),jl=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},_r=async function(e,t={}){let n=t.maxRecursiveDepth??rw;if(n===0)throw new jl("Max recursive depth reached");let[,o]=e.stringTuples().find(([u])=>u===nw)??[],i=await(t?.dns??Vd()).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=re(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 ip=hr(sp(),1),Ai=ip.default;var lw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:_r}},transportManager:{faultTolerance:Ht.FATAL_ALL}};async function ap(r){let e=Ai(lw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return e}function uw(r,e){try{if(typeof r=="string"&&r.length>0)return fw(r);if(typeof r=="number"&&isFinite(r))return e?.long?dw(r):hw(r);throw new Error("Value is not a string or number.")}catch(t){let n=pw(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function fw(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 _i=uw;function hw(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 dw(r){let e=Math.abs(r);return e>=864e5?Si(r,e,864e5,"day"):e>=36e5?Si(r,e,36e5,"hour"):e>=6e4?Si(r,e,6e4,"minute"):e>=1e3?Si(r,e,1e3,"second"):`${r} ms`}function Si(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function pw(r){return typeof r=="object"&&r!==null&&"message"in r}function Xl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=_i,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 w=m,b=Number(new Date),y=b-(l||b);w.diff=y,w.prev=l,w.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 k=g[x];_=B.call(w,k),g.splice(x,1),x--}return _}),t.formatArgs.call(w,g),(w.log||t.log).apply(w,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 Bi=vw(),mw=["#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 gw(){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 yw(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+_i(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 ww=console.debug??console.log??(()=>{});function bw(r){try{r?Bi?.setItem("debug",r):Bi?.removeItem("debug")}catch{}}function xw(){let r;try{r=Bi?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function vw(){try{return localStorage}catch{}}function Ew(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var cp=Xl({formatArgs:yw,save:bw,load:xw,useColors:gw,setupFormatters:Ew,colors:mw,storage:Bi,log:ww});var Ge=cp;Ge.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);Ge.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ge.formatters.m=r=>r==null?"undefined":Hc.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":lp(r.stack)??lp(r.message)??r.toString();function Aw(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 Ci(){return{forComponent(r){return Sw(r)}}}function Sw(r){let e=Aw(`${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 lp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Br(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 Ii(r){let e=rt(Z.decode(`z${r}`));return hn(e)}var Ut=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 Br(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 Br(this.map.values(),e=>e.key)}values(){return Br(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Cr=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 Br(this.set.entries(),e=>{let t=Ii(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ii(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Br(this.set.values(),e=>Ii(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 pp=Symbol.for("@achingbrain/uint8arraylist");function dp(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 Ti(r){return!!r?.[pp]}var we=class r{bufs;length;[pp]=!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(Ti(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(Ti(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=dp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=dp(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(Ti(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 Ve(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ve(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(!Ti(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=Ce(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=fe(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=fe(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=fe(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=Ce(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=fe(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=fe(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=fe(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=fe(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=fe(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(!ue(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 Yl=64,ut=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Yl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=fe(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?ue(this.fp,e.fp):!1}};function Ir(r,e){return Math.floor(Math.random()*(e-r))+r}var kr=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=Ir(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 Jl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},mp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gp=new globalThis.TextEncoder;function _w(r,e){let t=Jl[e],n=mp[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Bw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Jl[e],o=mp[e],s=r;for(;s.length>0;){let i=gp.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 Ql(r,{size:e=32,utf8Buffer:t}={}){if(!Jl[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 Bw(r,e,t);r=gp.encode(r)}return _w(r,e)}var Cw=hr(hp(),1);var wo={hash:r=>Number(Ql(r,{size:32})),hashV:(r,e)=>Iw(wo.hash(r,e))};function Iw(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var kw=500,bo=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??wo,this.seed=e.seed??Ir(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 kr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new kr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Ir(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize));for(let a=0;a<kw;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 kr(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}},Tw={1:.5,2:.84,4:.95,8:.98};function Lw(r=.001){return r>.002?2:r>1e-5?4:8}function yp(r,e=.001){let t=Lw(e),n=Tw[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Yl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Li=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??wo,this.seed=e.seed??Ir(0,Math.pow(2,10)),this.filterSeries=[new bo({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 bo({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 eu(r,e=.001,t){return new Li({...yp(r,e),...t??{}})}var xo;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((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:fe(0),payloadType:fe(0),payload:fe(0),signature:fe(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=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(xo||(xo={}));var Ni=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var bn=class r{static createFromProtobuf=async e=>{let t=xo.decode(e),n=fn(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=wp(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 Ni("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=xo.encode({publicKey:dt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ue(this.marshal(),e.marshal())}async validate(e){let t=wp(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},wp=(r,e,t)=>{let n=P(r),o=ke(n.byteLength),s=ke(e.length),i=ke(t.length);return new we(o,n,s,e,i,t)};function bp(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 xp="libp2p-peer-record",vp=Uint8Array.from([3,1]);var vo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Oe((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:fe(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=>Ue(s,n.codec()),n.decode=(s,i)=>Me(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((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:fe(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 Er('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=>Ue(n,r.codec()),r.decode=(n,o)=>Me(n,r.codec(),o)})(vo||(vo={}));var Tr=class r{static createFromProtobuf=e=>{let t=vo.decode(e),n=hn(rt(t.peerId)),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=xp;static CODEC=vp;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=vo.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||!bp(this.multiaddrs,e.multiaddrs))}};function Nw(r){return r[Symbol.asyncIterator]!=null}function Pw(r){if(Nw(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 Eo=Pw;var cr={},xn=r=>{r.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{xn.dispatchEvent("message",r,e)})};xn.addEventListener=(r,e)=>{cr[r]==null&&(cr[r]=[]),cr[r].push(e)};xn.removeEventListener=(r,e)=>{cr[r]!=null&&(cr[r]=cr[r].filter(t=>t===e))};xn.dispatchEvent=function(r,e,t){cr[r]!=null&&cr[r].forEach(n=>n(e,t))};var tu=xn;var ru="lock:worker:request-read",nu="lock:worker:release-read",ou="lock:master:grant-read",su="lock:worker:request-write",iu="lock:worker:release-write",au="lock:master:grant-write";var Ep=(r=21)=>Math.random().toString().substring(2);var Ap=(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?.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)})}}}))},Sp=(r,e,t,n)=>async()=>{let o=Ep();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(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)})},Dw={singleProcess:!1},_p=r=>{if(r=Object.assign({},Dw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return tu.addEventListener("message",Ap(t,"requestReadLock",ru,nu,ou)),tu.addEventListener("message",Ap(t,"requestWriteLock",su,iu,au)),t}return{isWorker:!0,readLock:t=>Sp(t,ru,ou,nu),writeLock:t=>Sp(t,su,au,iu)}};var Lr={},lr;async function cu(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Rw=(r,e)=>{if(lr.isWorker===!0)return{readLock:lr.readLock(r,e),writeLock:lr.writeLock(r,e)};let t=new sr({concurrency:1}),n;return{async readLock(){if(n!=null)return cu(n,e);n=new sr({concurrency:e.concurrency,autoStart:!1});let o=n,s=cu(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,cu(t,e)}}},Mw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function lu(r){let e=Object.assign({},Mw,r);return lr==null&&(lr=_p(e),lr.isWorker!==!0&&(lr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),lr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=Rw(e.name,e)),Lr[e.name]}var vn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((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:fe(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=>Ue(i,o.codec()),o.decode=(i,a)=>Me(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((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),Di.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=Di.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Ue(i,o.codec()),o.decode=(i,a)=>Me(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Pi.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 Er('Decode error - map field "addresses" had too many elements');a.addresses.push(Pi.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 Er('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 Wn('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 Wn('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=>Ue(o,r.codec()),r.decode=(o,s)=>Me(o,r.codec(),s)})(vn||(vn={}));var Pi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((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:fe(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=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(Pi||(Pi={}));var Di;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((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=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(Di||(Di={}));function En(r,e){let t=vn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=fn(t.publicKey);r=_l(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:re(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ot="/",Bp=new TextEncoder().encode(Ot),Ri=Bp[0],Nr=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]!==Ri)throw new Error("Invalid key")}toString(e="utf8"){return te(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ot))}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=Bp),this._buf[0]!==Ri){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ri,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ri;)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(Ot).slice(1)}type(){return Uw(this.baseNamespace())}name(){return Ow(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ot)||(e+=Ot),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ot):new r(e.slice(0,-1).join(Ot))}child(e){return this.toString()===Ot?e:e.toString()===Ot?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(),...Fw(e.map(t=>t.namespaces()))])}};function Uw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Ow(r){let e=r.split(":");return e[e.length-1]}function Fw(r){return[].concat(...r)}var uu="/peers/";function An(r){if(!Oo(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Nr(`${uu}${e}`)}async function Cp(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=re(o.multiaddr)),!ar(o.multiaddr))throw new R("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 Ui(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new R("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=Mi(d,{validate:Ip})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Mi(d,{validate:kp,map:Tp})}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=Mi([...a.entries()],{validate:Ip})}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=Mi([...h.entries()],{validate:kp,map:Tp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=dt(o.id.publicKey):e.publicKey!=null?f=dt(e.publicKey):r.publicKey!=null&&(f=dt(r.publicKey));let l={addresses:await Cp(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 Mi(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 Ip(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function kp(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Tp(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 Oi(r,e){let t=r.toString().split("/")[2],n=me.parse(t,We),o=hi(n);return En(o,e)}function Vw(r){return r==null?{}:{prefix:uu,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(Oi(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(Oi(t.key,t.value),Oi(n.key,n.value)))}}var Fi=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=lu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(An(e))}async delete(e){if(this.peerId.equals(e))throw new R("Cannot delete self peer");await this.datastore.delete(An(e))}async load(e){let t=await this.datastore.get(An(e));return En(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ui(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 Ui(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 Ui(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Vw(e??{}))){let o=Oi(t,n);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let t=await this.datastore.get(An(e)),n=En(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,o){let s=vn.encode(t);return n!=null&&ue(s,n)?{peer:En(e,s),previous:o,updated:!1}:(await this.datastore.put(An(e),s),{peer:En(e,s),previous:o,updated:!0})}};var fu=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 Fi(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 Eo(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await bn.openAndCertify(e,Tr.DOMAIN),o=hi(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=Tr.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 bn.createFromProtobuf(i.peerRecordEnvelope),c=Tr.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 Lp(r,e={}){return new fu(r,e)}var Vi=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 Hw(r){return r[Symbol.asyncIterator]!=null}function Kw(r){if(Hw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var hu=Kw;function qw(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 Np=qw;function $w(r){return r[Symbol.asyncIterator]!=null}function zw(r,e){let t=0;if($w(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Np(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 Pr=zw;function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r,e){return Gw(r)?async function*(){yield*(await Eo(r)).sort(e)}():function*(){yield*Eo(r).sort(e)}()}var du=Ww;function jw(r){return r[Symbol.asyncIterator]!=null}function Zw(r,e){return jw(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 pu=Zw;var Hi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value: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 hu(this.putMany(e,n)),e=[],await hu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>du(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=pu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>du(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=pu(n,e.limit)),n}};var Ki=class extends Hi{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 Vi;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 Nr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Nr(e)}};function Pp(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Xw={maxObservedAddresses:10},Yw=r=>r;function mu(r,e){let t=r.getPeerId();return t!=null&&wt(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var qi=4,$i=41,Jw=54,Qw=55,eb=6,tb=273,zi=class{log;components;listen;announce;appendAnnounce;observed;announceFilter;ipDomainMappings;publicAddressMappings;maxObservedAddresses;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Map,this.ipDomainMappings=new Map,this.publicAddressMappings=new Map,this.announceFilter=t.announceFilter??Yw,this.maxObservedAddresses=t.maxObservedAddresses??Xw.maxObservedAddresses,this._updatePeerStoreAddresses=Pp(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.getAddresses().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=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){if(this.observed.size===this.maxObservedAddresses)return;e=mu(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=mu(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=mu(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs();e.length===0&&(e=this.components.transportManager.getAddrs()),e=e.concat(...this.getAppendAnnounceAddrs(),Array.from(this.observed).filter(([s,i])=>i.confident).map(([s])=>re(s)));let t=[];e.forEach(s=>{let i=s.stringTuples(),a;if((i[0][0]===qi||i[0][0]===$i)&&i[1][0]===eb?a=`${i[0][1]}-${i[1][1]}-tcp`:(i[0][0]===qi||i[0][0]===$i)&&i[1][0]===tb&&(a=`${i[0][1]}-${i[1][1]}-udp`),a==null)return;let c=this.publicAddressMappings.get(a);if(c!=null)for(let u of c)i[0][0]=ir(u.externalIp)?qi:$i,i[0][1]=u.externalIp,i[1][1]=`${u.externalPort}`,t.push(re(`/${i.map(f=>[W(f[0]).name,f[1]].join("/")).join("/")}`))}),e=e.concat(t);let n=[];for(let s of e){let i=s.stringTuples(),a=!1;for(let[c,u]of this.ipDomainMappings.entries())if(u.confident)for(let f=0;f<i.length;f++)i[f][1]===c&&(i[f][0]===qi&&(i[f][0]=Jw,i[f][1]=u.domain,a=!0),i[f][0]===$i&&(i[f][0]=Qw,i[f][1]=u.domain,a=!0));a&&n.push(re(`/${i.map(c=>[W(c[0]).name,c[1]].join("/")).join("/")}`))}e=e.concat(n);let o=new Set;return e=e.filter(s=>{let i=s.toString();return o.has(i)?!1:(o.add(i),!0)}),this.announceFilter(Array.from(o).map(s=>{let i=re(s);return i.protos().pop()?.path===!0||i.getPeerId()===this.components.peerId.toString()?i:i.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}addDNSMapping(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=[...this.publicAddressMappings.entries()].some(([s,i])=>i.some(a=>a.externalIp===n));this.ipDomainMappings.set(n,{domain:e,confident:o})}),this._updatePeerStoreAddresses()}removeDNSMapping(e){for(let[t,n]of this.ipDomainMappings.entries())n.domain===e&&(this.log("remove DNS mapping for %s",e),this.ipDomainMappings.delete(t));this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.publicAddressMappings.get(i)??[];a.push({externalIp:n,externalPort:o}),this.publicAddressMappings.set(i,a);for(let[c,u]of this.ipDomainMappings.entries())c===n&&(u.confident=!0,this.ipDomainMappings.set(c,u));this._updatePeerStoreAddresses()}removePublicAddressMapping(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=(this.publicAddressMappings.get(i)??[]).filter(c=>c.externalIp!==n&&c.externalPort!==o);a.length===0?this.publicAddressMappings.delete(i):this.publicAddressMappings.set(i,a),this._updatePeerStoreAddresses()}};var Dp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Dp||(Dp={}));var Gi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Wi=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Sn=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"}},ji=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"}},Xi=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"}},Dr=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Yi=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"}},Rr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Qi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var gu=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=Ci())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Wo(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")}},nb=["metrics","connectionProtector","dns"],ob=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Rp(r={}){let e=new gu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!ob.includes(o)){let i=e.components[o];if(i==null&&!nb.includes(o))throw new Gi(`${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 Mp(r){let e={};for(let t of Object.values(r.components))for(let n of sb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of ib(t))if(e[n]!==!0)throw new Wi(`Service "${ab(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function sb(r){return Array.isArray(r?.[Pn])?r[Pn]:[]}function ib(r){return Array.isArray(r?.[Xa])?r[Xa]:[]}function ab(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Op=hr(Up(),1),cb=["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"],lb=cb.map(r=>new Op.Netmask(r));function yu(r){for(let e of lb)if(e.contains(r))return!0;return!1}function ub(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function fb(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 yu(o)}function hb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function db(r){let e=r.split(":"),t=e[e.length-1];return yu(t)}function pb(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 ea(r){return ir(r)?yu(r):ub(r)?fb(r):hb(r)?db(r):pn(r)?pb(r):void 0}var mb=r=>r.toString().split("/").slice(1),_n=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),z=r=>({match:e=>_n(t=>t===r).match(e),pattern:r}),Ur=()=>({match:r=>_n(e=>typeof e=="string").match(r),pattern:"{string}"}),Bo=()=>({match:r=>_n(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ee=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Z.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Co=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Kc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),j=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Pe=(...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(", ")})`}),G=(...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 ce(...r){function e(o){let s=mb(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{matchers:r,matches:t,exactMatch:n}}var ra=G(z("dns4"),Ur()),na=G(z("dns6"),Ur()),oa=G(z("dnsaddr"),Ur()),bu=G(z("dns"),Ur()),O3=ce(ra,j(ee())),F3=ce(na,j(ee())),V3=ce(oa,j(ee())),H3=ce(Pe(bu,oa,ra,na),j(ee())),Fp=G(z("ip4"),_n(ir)),Vp=G(z("ip6"),_n(pn)),xu=Pe(Fp,Vp),Ft=Pe(xu,bu,ra,na,oa),K3=ce(Pe(xu,G(Pe(bu,oa,ra,na),j(ee())))),q3=ce(Fp),$3=ce(Vp),z3=ce(xu),vu=G(Ft,z("tcp"),Bo()),Io=G(Ft,z("udp"),Bo()),Eu=ce(G(vu,j(ee()))),G3=ce(Io),Au=G(Io,z("quic"),j(ee())),sa=G(Io,z("quic-v1"),j(ee())),gb=Pe(Au,sa),W3=ce(Au),j3=ce(sa),wu=Pe(Ft,vu,Io,Au,sa),Hp=Pe(G(wu,z("ws"),j(ee()))),ko=ce(Hp),Kp=Pe(G(wu,z("wss"),j(ee())),G(wu,z("tls"),j(G(z("sni"),Ur())),z("ws"),j(ee()))),Su=ce(Kp),qp=G(Io,z("webrtc-direct"),j(Co()),j(Co()),j(ee())),_u=ce(qp),$p=G(sa,z("webtransport"),j(Co()),j(Co()),j(ee())),Bu=ce($p),ta=Pe(Hp,Kp,G(vu,j(ee())),G(gb,j(ee())),G(Ft,j(ee())),qp,$p,ee()),Z3=ce(ta),yb=G(ta,z("p2p-circuit"),ee()),To=ce(yb),wb=Pe(G(ta,z("p2p-circuit"),z("webrtc"),j(ee())),G(ta,z("webrtc"),j(ee())),G(z("webrtc"),j(ee()))),Cu=ce(wb),bb=Pe(G(Ft,z("tcp"),Bo(),z("http"),j(ee())),G(Ft,z("http"),j(ee()))),X3=ce(bb),xb=Pe(G(Ft,z("tcp"),Pe(G(z("443"),z("http")),G(Bo(),z("https"))),j(ee())),G(Ft,z("tls"),z("http"),j(ee())),G(Ft,z("https"),j(ee()))),Y3=ce(xb),vb=Pe(G(z("memory"),Ur(),j(ee()))),J3=ce(vb);var Eb=4,Ab=41;function zp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(ko.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Eb||t[0][0]===Ab?!!ea(`${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 Gp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Sb=new WeakMap;function _b({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Gp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Gp())},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}),Sb.set(l,()=>{c(s),s=null,i()}),l}}var Bb=_b(),Wp=Bb;var ia=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}},aa=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ca=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 Iu}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 ia("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 Wp(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)}},Iu=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 la(r){if(Oo(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:wt(t),r.forEach(n=>{if(!ar(n))throw new Kt("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let s=wt(o);if(e?.equals(s)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Cb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Cb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Zp="last-dial-failure",Xp="last-dial-success";var ua=100,fa=50;var Yp={maxConnections:ua,allow:[]},ha=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Yp.maxConnections,this.allow=t.allow??Yp.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){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 Ut;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 jp(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 he(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var da=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 da(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 da(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 ku=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pa(r={}){return Ib(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 Ib(r,e){e=e??{};let t=e.onEnd,n=new Bn,o,s,i,a=he(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,w)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(y){w(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=he()})}},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 w=g?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,y;w!=null&&(b=new Promise((x,A)=>{y=()=>{A(new ku)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,b])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},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 Tu=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 Cn(r,e,t,n){let o=new Tu(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 ma=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 ur(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ma(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ma(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 ga=class{deferred;signal;constructor(e){this.signal=e,this.deferred=he(),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 kb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ya=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=kb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,oe(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 ga(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 ur(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 In=class extends vt{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new aa;let n=new ya(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 Cn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Cn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Cn(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=pa({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 wa=class extends In{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Vt(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}var Tb=4,Lb=41,Nb=53,Pb=54,Db=55,Rb=56;function Lu(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!0;if(e===Nb||e===Pb||e===Db||e===Rb)return!1;if(e===Tb||e===Lb)return ea(t)??!1}catch{}return!0}function Mb(r,e){let t=Eu.exactMatch(r.multiaddr),n=Eu.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Su.exactMatch(r.multiaddr),s=Su.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=ko.exactMatch(r.multiaddr),a=ko.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Cu.exactMatch(r.multiaddr),u=Cu.exactMatch(e.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=_u.exactMatch(r.multiaddr),l=_u.exactMatch(e.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=Bu.exactMatch(r.multiaddr),h=Bu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Ub(r,e){let t=Lu(r.multiaddr),n=Lu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ob(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Fb(r,e){let t=To.exactMatch(r.multiaddr),n=To.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Jp(r){return r.sort(Mb).sort(Ob).sort(Fb).sort(Ub)}async function Qp(r,e){let t=!1;for(let o of gn.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 ba={maxParallelDials:fa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:_r}},xa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??ba.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??ba.maxDialQueueLength,this.dialTimeout=t.dialTimeout??ba.dialTimeout,this.connections=t.connections??new Ut,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,oe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))gn.set(n,o);this.queue=new wa({concurrency:t.maxParallelDials??ba.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,oe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=la(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?.status==="open")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 $r("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=Vt([this.shutDownController.signal,a.signal]);oe(1/0,c);let 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 $r("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:{[Xp]: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:{[Zp]: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 $o(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??Ru,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:re(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new $r("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 Qp(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 Dr("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=this.addressSorter==null?Jp(u):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=>!To.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var va=class extends In{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var im=hr(om(),1);var Hb=Object.prototype.toString,Kb=r=>Hb.call(r)==="[object Error]",qb=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 Mu(r){return r&&Kb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:qb.has(r.message):!1}var Uu=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}},sm=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ou(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let o=im.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 Uu)throw c.originalError;if(c instanceof TypeError&&!Mu(c))throw c;if(sm(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){sm(u,a,e),i(),n(u)}}})})}var Ea=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new va({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);am(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Ou(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",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Za)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>am(t)]});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()}};function am(r){for(let e of r.tags.keys())if(e.startsWith(Za))return!0;return!1}var Ru=50,Fu={maxConnections:ua,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Aa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Fu.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Ut,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>re(n)),this.deny=(t.deny??[]).map(n=>re(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Fu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ca({points:t.inboundConnectionThreshold??Fu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ha({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new xa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??fa,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:_r},connections:this.connections}),this.reconnectQueue=new Ea({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await af(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await cf(this.reconnectQueue,this.dialQueue,this.connectionPruner);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}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),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.started)throw new xt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=la(e);if(this.peerId.equals(n))throw new qr("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??Ru});if(o.status!=="open")throw new Kr("Remote closed connection during opening");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 Kt("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}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=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var kn=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 Gb=1.2,Wb=2,jb=2e3,Sa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new kn(e.interval??5e3),this.failure=new kn(e.interval??5e3),this.next=new kn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Wb,this.timeoutMultiplier=e.timeoutMultiplier??Gb,this.minTimeout=e.minTimeout??jb,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=Vt([e.signal,n]);return oe(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 Vu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=he(),this.haveNext=he()}[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=he(),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=he(),await ur(this.readNext.promise,t?.signal,t)}};function cm(){return new Vu}var _a=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Hu=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ku=class extends Hu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ba(r,e){let t=cm();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 we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Ku("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 we:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new _a("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 Zb=1e4,Xb="1.0.0",Yb="ping",Jb="ipfs",lm=32,Qb=!0,Ca=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Jb}/${Yb}/${Xb}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Zb,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Qb,this.timeout=new Sa({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Pn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,oe(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=Ba(o);t=Date.now(),await Promise.all([s.write(ln(lm),{signal:n}),s.read(lm,{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 ex(r){return r[Symbol.asyncIterator]!=null}function tx(...r){let e=[];for(let t of r)ex(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=pa({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 Lo=tx;var Ia=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 Sn("No content routers available");let n=this,o=new Cr;for await(let s of Lo(...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 Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new xt;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new xt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ka=globalThis.CustomEvent??Event;async function*qu(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=he(),a=he(),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=he(),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 ka("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ka("task-complete"))})}c=!0,o.dispatchEvent(new ka("task-complete"))}catch(p){u=p,o.dispatchEvent(new ka("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=he(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var Ta=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 ji("Should not try to find self");let n=this,o=Lo(...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 Vo}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ao("No peer routers available");let n=this,o=eu(1024);for await(let s of qu(async function*(){let i=Lo(...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 La=class extends vt{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,oe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,oe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Vt([this.shutdownController.signal,e?.signal]);oe(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=he(),yield(await Cn(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,oe(1/0,this.walkController.signal);let e=Vt([this.walkController.signal,this.shutdownController.signal]);oe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=ln(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 ur(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 $u=32,zu=64,Na=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 Xi(`Handler already registered for protocol ${e}`);let o=Ai.bind({ignoreUndefined:!0})({maxInboundStreams:$u,maxOutboundStreams:zu},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 R("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 Gu=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 um(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Gu({name:e,metrics:t}):n=new Map,n}var Pa=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=um({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ht.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`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 Qi(`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 xt("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!==Ht.NO_FATAL)throw new Dr(`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===Ht.FATAL_ALL)throw new Dr(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 _e="/multistream/1.0.0";var Da=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ra=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ma=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function No(r,e={}){let t=Ba(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??ke;return{read:async i=>{let a=-1,c=new we;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 Da("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ma("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ra("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var rx=P(`
|
|
7
|
-
`);async function
|
|
8
|
-
`),i=P(`${
|
|
9
|
-
`);await
|
|
10
|
-
`),t),t.log.trace("select: reading protocol response");let u=await fr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new
|
|
6
|
+
`)}`:`${t} :`}};Th=rr;T.Constructed=Th;rr.NAME="CONSTRUCTED";var Lo=class extends Le{fromBER(e,t,n){return t}toBER(e){return lt}};Lo.override="EndOfContentValueBlock";var Lh,No=class extends Ae{constructor(e={}){super(e,Lo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Lh=No;T.EndOfContent=Lh;No.NAME=Jn;var Nh,on=class extends Ae{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 s=new Uint8Array(n);s[0]=5,s[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Nh=on;T.Null=Nh;on.NAME="NULL";var Po=class extends Rt(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 s=q.BufferSourceConverter.toUint8Array(e);return Dt(this,s,t,n)?(this.valueHexView=s.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,pl.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Po.NAME="BooleanValueBlock";var Ph,Do=class extends Ae{constructor(e={}){super(e,Po),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}`}};Ph=Do;T.Boolean=Ph;Do.NAME="BOOLEAN";var Ro=class extends Rt(gt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=gt.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let o=0;o<this.value.length;o++){let i=this.value[o].constructor.NAME;if(i===Jn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Bh)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?gt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Ro.NAME="OctetStringValueBlock";var Dh,Mo=class r extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ro),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 o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(o.byteLength){let i=ui(o,0,o.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?rr.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)}};Dh=Mo;T.OctetString=Dh;Mo.NAME=Bh;var Uo=class extends Rt(gt){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 s=-1;if(this.isConstructed){if(s=gt.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===Jn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Ch)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 s}let o=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,o,t,n))return-1;let i=o.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=ui(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 gt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Uo.NAME="BitStringValueBlock";var Rh,an=class extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Uo),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 rr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Rh=an;T.BitString=Rh;an.NAME=Ch;var Mh;function Ey(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.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=o[i-l]+a[c-l]+t[0];break;default:u=o[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=o.length:o=So(new Uint8Array([u%10]),o);break;default:o[i-l]=u%10}}return t[0]>0&&(o=So(t,o)),o}function _h(r){if(r>=Xn.length)for(let e=Xn.length;e<=r;e++){let t=new Uint8Array([0]),n=Xn[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let o=new Uint8Array([(n[s]<<1)+t[0]]);t[0]=o[0]/10,n[s]=o[0]%10}t[0]>0&&(n=So(t,n)),Xn.push(n)}return Xn[r]}function Ay(r,e){let t=0,n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=o[i-f]-a[c-f]-t,!0){case u<0:t=1,o[i-f]=u+10;break;default:t=0,o[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=o[i-f]-t,u<0)t=1,o[i-f]=u+10;else{t=0,o[i-f]=u;break}return o.slice()}var Qn=class extends Rt(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=pl.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Eh(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,s=0){let o=this.fromBER(e,t,n);if(o===-1)return o;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}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 s=super.fromBER(e,t,n);return s===-1||this.setValueHex(),s}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,s,o=this.valueHexView,i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let u=0;u<8;u++){if((s&1)===1)switch(n){case e:t=Ay(_h(n),t),i="-";break;default:t=Ey(t,_h(n))}n++,s>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Sh.charAt(t[c]));return a===!1&&(i+=Sh.charAt(0)),i}};Mh=Qn;Qn.NAME="IntegerValueBlock";Object.defineProperty(Mh.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Uh,Se=class r extends Ae{constructor(e={}){super(e,Qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return _o(),BigInt(this.valueBlock.toString())}static fromBigInt(e){_o();let t=BigInt(e),n=new Yn,s=t.toString(16).replace(/^-/,""),o=new Uint8Array(q.Convert.FromHex(s));if(t<0){let a=new Uint8Array(o.length+(o[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 o[0]&128&&n.write(new Uint8Array([0])),n.write(o);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()}`}};Uh=Se;T.Integer=Uh;Se.NAME="INTEGER";var Oh,Oo=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Oh=Oo;T.Enumerated=Oh;Oo.NAME="ENUMERATED";var es=class extends Rt(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 s=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,!!(o[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,o[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=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){_o();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+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 s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}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}}};es.NAME="sidBlock";var Fo=class extends Le{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new es;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,lt;t.push(s)}return ml(t)}fromString(e){this.value=[];let t=0,n=0,s="",o=!1;do if(n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1,o){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(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{let i=new es;if(s>Number.MAX_SAFE_INTEGER){_o();let a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!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 s=this.value[n].toString();n!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}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}};Fo.NAME="ObjectIdentifierValueBlock";var Fh,cn=class extends Ae{constructor(e={}){super(e,Fo),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()}}};Fh=cn;T.ObjectIdentifier=Fh;cn.NAME="OBJECT IDENTIFIER";var ts=class extends Rt(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let s=q.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,!!(o[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,o[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=Sr(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 s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}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}}};ts.NAME="relativeSidBlock";var Vo=class extends Le{constructor({value:e=ln,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new ts;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,t){let n=[];for(let s=0;s<this.value.length;s++){let o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,lt;n.push(o)}return ml(n)}fromString(e){this.value=[];let t=0,n=0,s="";do{n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1;let o=new ts;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}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 s=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}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}};Vo.NAME="RelativeObjectIdentifierValueBlock";var Vh,Ho=class extends Ae{constructor(e={}){super(e,Vo),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()}}};Vh=Ho;T.RelativeObjectIdentifier=Vh;Ho.NAME="RelativeObjectIdentifier";var Hh,Nt=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Hh=Nt;T.Sequence=Hh;Nt.NAME="SEQUENCE";var Kh,Ko=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Kh=Ko;T.Set=Kh;Ko.NAME="SET";var qo=class extends Rt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ln}toJSON(){return{...super.toJSON(),value:this.value}}};qo.NAME="StringValueBlock";var $o=class extends qo{};$o.NAME="SimpleStringValueBlock";var Fe=class extends Io{constructor({...e}={}){super(e,$o)}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 s=0;s<t;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};Fe.NAME="SIMPLE STRING";var zo=class extends Fe{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}};zo.NAME="Utf8StringValueBlock";var qh,Pt=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};qh=Pt;T.Utf8String=qh;Pt.NAME="UTF8String";var Go=class extends Fe{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))}};Go.NAME="BmpStringValueBlock";var $h,Wo=class extends Go{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};$h=Wo;T.BmpString=$h;Wo.NAME="BMPString";var jo=class extends Fe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+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 s=0;s<t;s++){let o=tr(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}};jo.NAME="UniversalStringValueBlock";var zh,Zo=class extends jo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};zh=Zo;T.UniversalString=zh;Zo.NAME="UniversalString";var Gh,Xo=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Gh=Xo;T.NumericString=Gh;Xo.NAME="NumericString";var Wh,Yo=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Wh=Yo;T.PrintableString=Wh;Yo.NAME="PrintableString";var jh,Jo=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};jh=Jo;T.TeletexString=jh;Jo.NAME="TeletexString";var Zh,Qo=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Zh=Qo;T.VideotexString=Zh;Qo.NAME="VideotexString";var Xh,ei=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Xh=ei;T.IA5String=Xh;ei.NAME="IA5String";var Yh,ti=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Yh=ti;T.GraphicString=Yh;ti.NAME="GraphicString";var Jh,rs=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Jh=rs;T.VisibleString=Jh;rs.NAME="VisibleString";var Qh,ri=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Qh=ri;T.GeneralString=Qh;ri.NAME="GeneralString";var ed,ni=class extends Fe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};ed=ni;T.CharacterString=ed;ni.NAME="CharacterString";var td,ns=class extends rs{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 s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}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 s=0;s<e.length;s++)n[s]=e.charCodeAt(s);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 s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,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]=ze(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ze(this.month,2),t[2]=ze(this.day,2),t[3]=ze(this.hour,2),t[4]=ze(this.minute,2),t[5]=ze(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}}};td=ns;T.UTCTime=td;ns.NAME="UTCTime";var rd,si=class extends ns{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="",s="",o=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");o=l.valueOf(),s=n.substring(0,u)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*o;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 s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*o;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*o;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(s);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(ze(this.year,4)),t.push(ze(this.month,2)),t.push(ze(this.day,2)),t.push(ze(this.hour,2)),t.push(ze(this.minute,2)),t.push(ze(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ze(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};rd=si;T.GeneralizedTime=rd;si.NAME="GeneralizedTime";var nd,oi=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};nd=oi;T.DATE=nd;oi.NAME="DATE";var sd,ii=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};sd=ii;T.TimeOfDay=sd;ii.NAME="TimeOfDay";var od,ai=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};od=ai;T.DateTime=od;ai.NAME="DateTime";var id,ci=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};id=ci;T.Duration=id;ci.NAME="Duration";var ad,li=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ad=li;T.TIME=ad;li.NAME="TIME";function te(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function un(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return wh(r)}var ss=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},os=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},fi=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var cd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new fi("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 nr=cd;async function ld(r){let e=await nr.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 _y(e);return{privateKey:t[0],publicKey:t[1]}}async function ud(r,e){let t=await nr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await nr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function fd(r,e,t){let n=await nr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return nr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function _y(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([nr.get().subtle.exportKey("jwk",r.privateKey),nr.get().subtle.exportKey("jwk",r.publicKey)])}function wl(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return P(r.n,"base64url").length*8}var fn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=is.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return me.createV1(114,this._multihash)}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return fd(this._key,t,e)}},as=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=is.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return ud(this._key,e)}};var hi=8192,bl=18;function hd(r){let{result:e}=yl(r),t=e.valueBlock.value;return{n:yt(t[1]),e:yt(t[2]),d:yt(t[3]),p:yt(t[4]),q:yt(t[5]),dp:yt(t[6]),dq:yt(t[7]),qi:yt(t[8]),kty:"RSA",alg:"RS256"}}function By(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 R("JWK was missing components");let t=new Nt({value:[new Se({value:0}),Se.fromBigInt(wt(P(r.n,"base64url"))),Se.fromBigInt(wt(P(r.e,"base64url"))),Se.fromBigInt(wt(P(r.d,"base64url"))),Se.fromBigInt(wt(P(r.p,"base64url"))),Se.fromBigInt(wt(P(r.q,"base64url"))),Se.fromBigInt(wt(P(r.dp,"base64url"))),Se.fromBigInt(wt(P(r.dq,"base64url"))),Se.fromBigInt(wt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function dd(r){let{result:e}=yl(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:yt(t[0]),e:yt(t[1])}}function xl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");let t=new Nt({value:[new Nt({value:[new cn({value:"1.2.840.113549.1.1.1"}),new on]}),new an({valueHex:new Nt({value:[Se.fromBigInt(wt(P(r.n,"base64url"))),Se.fromBigInt(wt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function yt(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return te(e,"base64url")}function wt(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 pd(r){let e=hd(r);return md(e)}function vl(r){let e=dd(r);if(wl(e)>hi)throw new Kr("Key size is too large");let t=vo(mt.encode({Type:ye.RSA,Data:r})),n=tt(bl,t);return new fn(e,n)}function md(r){if(wl(r)>hi)throw new R("Key size is too large");let e=gd(r),t=vo(mt.encode({Type:ye.RSA,Data:xl(e.publicKey)})),n=tt(bl,t);return new as(e.privateKey,new fn(e.publicKey,n))}async function El(r){if(r>hi)throw new R("Key size is too large");let e=await ld(r),t=vo(mt.encode({Type:ye.RSA,Data:xl(e.publicKey)})),n=tt(bl,t);return new as(e.privateKey,new fn(e.publicKey,n))}function gd(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Cy=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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),Al=class extends en{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|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)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=or[l-15],h=or[l-2],p=nt(d,7)^nt(d,18)^d>>>3,m=nt(h,17)^nt(h,19)^h>>>10;or[l]=m+or[l-7]+p+or[l-16]|0}let{A:n,B:s,C:o,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+Df(a,c,u)+Cy[l]+or[l]|0,m=(nt(n,2)^nt(n,13)^nt(n,22))+Rf(n,s,o)|0;f=u,u=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+m|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,u,f)}roundClean(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var yd=Js(()=>new Al);var di=class extends Qr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Lf(e);let n=Vn(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 s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),o.fill(0)}update(e){return Jr(this),this.iHash.update(e),this}digestInto(e){Jr(this),Yr(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,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()}},Sl=(r,e,t)=>new di(r,e).update(t).digest();Sl.create=(r,e)=>new di(r,e);function wd(r){r.lowS!==void 0&&st("lowS",r.lowS),r.prehash!==void 0&&st("prehash",r.prehash)}function Iy(r){let e=qn(r);dt(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:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:ky,hexToBytes:Ty}=no,Mt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Mt;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,s=pr(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?pr(s.length/2|128):"";return pr(r)+o+s+e},decode(r,e){let{Err:t}=Mt,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 s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&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}=Mt;if(r<Ut)throw new e("integer: negative integers are not allowed");let t=pr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Mt;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 ky(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Mt,s=typeof r=="string"?Ty(r):r;tn(s);let{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{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}=Mt,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Ut=BigInt(0),ve=BigInt(1),AE=BigInt(2),bd=BigInt(3),SE=BigInt(4);function Ly(r){let e=Iy(r),{Fp:t}=e,n=Yt(e.n,e.nBitLength),s=e.toBytes||((m,g,w)=>{let b=g.toAffine();return kt(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),o=e.fromBytes||(m=>{let g=m.subarray(1),w=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:w,y:b}});function i(m){let{a:g,b:w}=e,b=t.sqr(m),y=t.mul(b,m);return t.add(t.add(y,t.mul(m,g)),w)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Hn(m,ve,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:b,n:y}=e;if(g&&typeof m!="bigint"){if(jt(m)&&(m=Ct(m)),typeof m!="string"||!g.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let x;try{x=typeof m=="bigint"?m:It(ae("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return b&&(x=ee(x,y)),qe("private key",x,ve,y),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=yr((m,g)=>{let{px:w,py:b,pz:y}=m;if(t.eql(y,t.ONE))return{x:w,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(y));let A=t.mul(w,g),_=t.mul(b,g),v=t.mul(y,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=yr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=m.toAffine();if(!t.isValid(g)||!t.isValid(w))throw new Error("bad point: x or y not FE");let b=t.sqr(w),y=i(g);if(!t.eql(b,y))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,w,b){if(this.px=g,this.py=w,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:w,y:b}=g||{};if(!g||!t.isValid(w)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let y=x=>t.eql(x,t.ZERO);return y(w)&&y(b)?d.ZERO:new d(w,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let w=t.invertBatch(g.map(b=>b.pz));return g.map((b,y)=>b.toAffine(w[y])).map(d.fromAffine)}static fromHex(g){let w=d.fromAffine(o(ae("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return ao(d,n,g,w)}_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:w,py:b,pz:y}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(w,_),t.mul(x,y)),B=t.eql(t.mul(b,_),t.mul(A,y));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:w}=e,b=t.mul(w,bd),{px:y,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,k=t.mul(y,y),J=t.mul(x,x),H=t.mul(A,A),V=t.mul(y,x);return V=t.add(V,V),B=t.mul(y,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,H),v=t.add(_,v),_=t.sub(J,v),v=t.add(J,v),v=t.mul(_,v),_=t.mul(V,_),B=t.mul(b,B),H=t.mul(g,H),V=t.sub(k,H),V=t.mul(g,V),V=t.add(V,B),B=t.add(k,k),k=t.add(B,k),k=t.add(k,H),k=t.mul(k,V),v=t.add(v,k),H=t.mul(x,A),H=t.add(H,H),k=t.mul(H,V),_=t.sub(_,k),B=t.mul(H,J),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:w,py:b,pz:y}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,k=t.ZERO,J=e.a,H=t.mul(e.b,bd),V=t.mul(w,x),D=t.mul(b,A),I=t.mul(y,_),N=t.add(w,b),S=t.add(x,A);N=t.mul(N,S),S=t.add(V,D),N=t.sub(N,S),S=t.add(w,y);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(V,I),S=t.sub(S,E),E=t.add(b,y),v=t.add(A,_),E=t.mul(E,v),v=t.add(D,I),E=t.sub(E,v),k=t.mul(J,S),v=t.mul(H,I),k=t.add(v,k),v=t.sub(D,k),k=t.add(D,k),B=t.mul(v,k),D=t.add(V,V),D=t.add(D,V),I=t.mul(J,I),S=t.mul(H,S),D=t.add(D,I),I=t.sub(V,I),I=t.mul(J,I),S=t.add(S,I),V=t.mul(D,S),B=t.add(B,V),V=t.mul(E,S),v=t.mul(N,v),v=t.sub(v,V),V=t.mul(N,D),k=t.mul(E,k),k=t.add(k,V),new d(v,B,k)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){let{endo:w,n:b}=e;qe("scalar",g,Ut,b);let y=d.ZERO;if(g===Ut)return y;if(this.is0()||g===ve)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:x,k1:A,k2neg:_,k2:v}=w.splitScalar(g),B=y,k=y,J=this;for(;A>Ut||v>Ut;)A&ve&&(B=B.add(J)),v&ve&&(k=k.add(J)),J=J.double(),A>>=ve,v>>=ve;return x&&(B=B.negate()),_&&(k=k.negate()),k=new d(t.mul(k.px,w.beta),k.py,k.pz),B.add(k)}multiply(g){let{endo:w,n:b}=e;qe("scalar",g,ve,b);let y,x;if(w){let{k1neg:A,k1:_,k2neg:v,k2:B}=w.splitScalar(g),{p:k,f:J}=this.wNAF(_),{p:H,f:V}=this.wNAF(B);k=p.constTimeNegate(A,k),H=p.constTimeNegate(v,H),H=new d(t.mul(H.px,w.beta),H.py,H.pz),y=k.add(H),x=J.add(V)}else{let{p:A,f:_}=this.wNAF(g);y=A,x=_}return d.normalizeZ([y,x])[0]}multiplyAndAddUnsafe(g,w,b){let y=d.BASE,x=(_,v)=>v===Ut||v===ve||!_.equals(y)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,w).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:w}=e;if(g===ve)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:w}=e;return g===ve?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return st("isCompressed",g),this.assertValidity(),s(d,this,g)}toHex(g=!0){return st("isCompressed",g),Ct(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=io(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Ny(r){let e=qn(r);return dt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xd(r){let e=Ny(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(I){return ee(I,n)}function a(I){return so(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=Ly({...e,toBytes(I,N,S){let E=N.toAffine(),C=t.toBytes(E.x),L=kt;return st("isCompressed",S),S?L(Uint8Array.from([N.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,t.toBytes(E.y))},fromBytes(I){let N=I.length,S=I[0],E=I.subarray(1);if(N===s&&(S===2||S===3)){let C=It(E);if(!Hn(C,ve,t.ORDER))throw new Error("Point is not on curve");let L=f(C),M;try{M=t.sqrt(L)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let U=(M&ve)===ve;return(S&1)===1!==U&&(M=t.neg(M)),{x:C,y:M}}else if(N===o&&S===4){let C=t.fromBytes(E.subarray(0,t.BYTES)),L=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:C,y:L}}else{let C=s,L=o;throw new Error("invalid Point, expected length of "+C+", or uncompressed "+L+", got "+N)}}}),d=I=>Ct(Xt(I,e.nByteLength));function h(I){let N=n>>ve;return I>N}function p(I){return h(I)?i(-I):I}let m=(I,N,S)=>It(I.slice(N,S));class g{constructor(N,S,E){this.r=N,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(N){let S=e.nByteLength;return N=ae("compactSignature",N,S*2),new g(m(N,0,S),m(N,S,2*S))}static fromDER(N){let{r:S,s:E}=Mt.toSig(ae("DER",N));return new g(S,E)}assertValidity(){qe("r",this.r,ve,n),qe("s",this.s,ve,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:S,s:E,recovery:C}=this,L=_(ae("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let M=C===2||C===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=C&1?"03":"02",K=c.fromHex(U+d(M)),$=a(M),O=i(-L*$),Q=i(E*$),ne=c.BASE.multiplyAndAddUnsafe(K,O,Q);if(!ne)throw new Error("point at infinify");return ne.assertValidity(),ne}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return mr(this.toDERHex())}toDERHex(){return Mt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return mr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let I=Ec(e.n);return $f(e.randomBytes(I),e.n)},precompute(I=8,N=c.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function b(I,N=!0){return c.fromPrivateKey(I).toRawBytes(N)}function y(I){let N=jt(I),S=typeof I=="string",E=(N||S)&&I.length;return N?E===s||E===o:S?E===2*s||E===2*o:I instanceof c}function x(I,N,S=!0){if(y(I))throw new Error("first arg must be private key");if(!y(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(u(I)).toRawBytes(S)}let A=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=It(I),S=I.length*8-e.nBitLength;return S>0?N>>BigInt(S):N},_=e.bits2int_modN||function(I){return i(A(I))},v=Kn(e.nBitLength);function B(I){return qe("num < 2^"+e.nBitLength,I,Ut,v),Xt(I,e.nByteLength)}function k(I,N,S=J){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:C}=e,{lowS:L,prehash:M,extraEntropy:U}=S;L==null&&(L=!0),I=ae("msgHash",I),wd(S),M&&(I=ae("prehashed msgHash",E(I)));let K=_(I),$=u(N),O=[B($),B(K)];if(U!=null&&U!==!1){let xe=U===!0?C(t.BYTES):U;O.push(ae("extraEntropy",xe))}let Q=kt(...O),ne=K;function be(xe){let Ee=A(xe);if(!l(Ee))return;let Be=a(Ee),Ke=c.BASE.multiply(Ee).toAffine(),De=i(Ke.x);if(De===Ut)return;let ht=i(Be*i(ne+De*$));if(ht===Ut)return;let xt=(Ke.x===De?0:2)|Number(Ke.y&ve),Nn=ht;return L&&h(ht)&&(Nn=p(ht),xt^=1),new g(De,Nn,xt)}return{seed:Q,k2sig:be}}let J={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function V(I,N,S=J){let{seed:E,k2sig:C}=k(I,N,S),L=e;return wc(L.hash.outputLen,L.nByteLength,L.hmac)(E,C)}c.BASE._setWindowSize(8);function D(I,N,S,E=H){let C=I;N=ae("msgHash",N),S=ae("publicKey",S);let{lowS:L,prehash:M,format:U}=E;if(wd(E),"strict"in E)throw new Error("options.strict was renamed to lowS");if(U!==void 0&&U!=="compact"&&U!=="der")throw new Error("format must be compact or der");let K=typeof C=="string"||jt(C),$=!K&&!U&&typeof C=="object"&&C!==null&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!K&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,Q;try{if($&&(O=new g(C.r,C.s)),K){try{U!=="compact"&&(O=g.fromDER(C))}catch(xt){if(!(xt instanceof Mt.Err))throw xt}!O&&U!=="der"&&(O=g.fromCompact(C))}Q=c.fromHex(S)}catch{return!1}if(!O||L&&O.hasHighS())return!1;M&&(N=e.hash(N));let{r:ne,s:be}=O,xe=_(N),Ee=a(be),Be=i(xe*Ee),Ke=i(ne*Ee),De=c.BASE.multiplyAndAddUnsafe(Q,Be,Ke)?.toAffine();return De?i(De.x)===ne:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:V,verify:D,ProjectivePoint:c,Signature:g,utils:w}}function Py(r){return{hash:r,hmac:(e,...t)=>Sl(r,e,fc(...t)),randomBytes:Qs}}function vd(r,e){let t=n=>xd({...r,...Py(n)});return Object.freeze({...t(e),create:t})}var Sd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ed=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Dy=BigInt(1),_l=BigInt(2),Ad=(r,e)=>(r+e/_l)/e;function Ry(r){let e=Sd,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ie(f,t,e)*f%e,d=ie(l,t,e)*f%e,h=ie(d,_l,e)*u%e,p=ie(h,s,e)*h%e,m=ie(p,o,e)*p%e,g=ie(m,a,e)*m%e,w=ie(g,c,e)*g%e,b=ie(w,a,e)*m%e,y=ie(b,t,e)*f%e,x=ie(y,i,e)*p%e,A=ie(x,n,e)*u%e,_=ie(A,_l,e);if(!Bl.eql(Bl.sqr(_),r))throw new Error("Cannot find square root");return _}var Bl=Yt(Sd,void 0,void 0,{sqrt:Ry}),Ye=vd({a:BigInt(0),b:BigInt(7),Fp:Bl,n:Ed,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Ed,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Dy*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=Ad(o*r,e),c=Ad(-n*r,e),u=ee(r-a*t-c*s,e),f=ee(-a*n-c*o,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}}}},yd),PE=BigInt(0);var DE=Ye.ProjectivePoint;function Ve(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ce(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function Cl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function _d(r,e){let t=rn.digest(e instanceof Uint8Array?e:e.subarray());if(Cl(t))return t.then(({digest:n})=>Ye.sign(n,r).toDERRawBytes()).catch(n=>{throw new ss(String(n))});try{return Ye.sign(t.digest,r).toDERRawBytes()}catch(n){throw new ss(String(n))}}function Bd(r,e,t){let n=rn.digest(t instanceof Uint8Array?t:t.subarray());if(Cl(n))return n.then(({digest:s})=>Ye.verify(e,s,r)).catch(s=>{throw new os(String(s))});try{return Ye.verify(e,n.digest,r)}catch(s){throw new os(String(s))}}var cs=class{type="secp256k1";raw;_key;constructor(e){this._key=kd(e),this.raw=Cd(this._key)}toMultihash(){return _t.digest(pt(this))}toCID(){return me.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}verify(e,t){return Bd(this._key,t,e)}},pi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Id(e),this.publicKey=new cs(t??Td(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ue(this.raw,e.raw)}sign(e){return _d(this.raw,e)}};function Il(r){return new cs(r)}async function Ld(){let r=My();return new pi(r)}function Cd(r){return Ye.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Id(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new Pn(String(e))}}function kd(r){try{return Ye.ProjectivePoint.fromHex(r),r}catch(e){throw new Kr(String(e))}}function Td(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new Pn(String(e))}}function My(){return Ye.utils.randomPrivateKey()}async function Nd(r,e){if(r==="Ed25519")return th();if(r==="secp256k1")return Ld();if(r==="RSA")return El(e??2048);throw new $t}function hn(r){let{Type:e,Data:t}=mt.decode(r),n=t??new Uint8Array;switch(e){case ye.RSA:return vl(n);case ye.Ed25519:return kc(n);case ye.secp256k1:return Il(n);default:throw new $t}}function Pd(r){let{Type:e,Data:t}=mt.decode(r.digest),n=t??new Uint8Array;switch(e){case ye.Ed25519:return kc(n);case ye.secp256k1:return Il(n);default:throw new $t}}function pt(r){return mt.encode({Type:ye[r.type],Data:r.raw})}var Dd=Symbol.for("nodejs.util.inspect.custom"),Uy=114,ls=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()})`}[Fs]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return me.createV1(Uy,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ue(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ue(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Dd](){return`PeerId(${this.toString()})`}},us=class extends ls{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},fs=class extends ls{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},hs=class extends ls{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Oy=2336,ds=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=_t.digest(P(this.url))}[Dd](){return`PeerId(${this.url})`}[Fs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return me.createV1(Oy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}};var Fy=114,Rd=2336;function bt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=rt(X.decode(`z${r}`));else{if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=rt(e.decode(r))}return dn(t)}function kl(r){if(r.type==="Ed25519")return new fs({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new hs({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new us({multihash:r.toCID().multihash,publicKey:r});throw new $t}function Md(r){return kl(r.publicKey)}function dn(r){if(Hy(r))return new us({multihash:r});if(Vy(r))try{let e=Pd(r);if(e.type==="Ed25519")return new fs({multihash:r,publicKey:e});if(e.type==="secp256k1")return new hs({multihash:r,publicKey:e})}catch{let t=te(r.digest);return new ds(new URL(t))}throw new $s("Supplied PeerID Multihash is invalid")}function mi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Fy&&r.code!==Rd)throw new qs("Supplied PeerID CID is invalid");if(r.code===Rd){let e=te(r.multihash.digest);return new ds(new URL(e))}return dn(r.multihash)}function Vy(r){return r.code===_t.code}function Hy(r){return r.code===rn.code}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ll=hr(Od(),1);var ms=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Fd=r=>globalThis.DOMException===void 0?new Nl(r):new DOMException(r),Vd=r=>{let e=r.reason===void 0?Fd("This operation was aborted."):r.reason;return e instanceof Error?e:Fd(e)};function gs(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={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(Vd(d));let h=()=>{f(Vd(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new ms;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?u():s instanceof Error?f(s):(l.message=s??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function Pl(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var ys=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 s=Pl(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,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 ir=class extends Ll.default{#e;#t;#o=0;#a;#c;#p=0;#n;#l;#r;#m;#s=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:ys,...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.#o<this.#a}get#x(){return this.#s<this.#u}#v(){this.#s--,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.#o=this.#e?this.#s: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.#s===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.#o===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#s: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,s)=>{this.#r.enqueue(async()=>{this.#s++,this.#o++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=gs(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#S(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof ms&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}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.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function yi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Dl=60;function wi(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?te(e.data):e.data}))}}var $y=4;function Rl(r,e={}){let t=new ir({concurrency:e.queryConcurrency??$y});return async(n,s={})=>{let o=new URLSearchParams;o.set("name",n),yi(s.types).forEach(a=>{o.append("type",Ze[a])}),s.onProgress?.(new de("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wi(await a.json());return s.onProgress?.(new de("dns:response",{detail:c})),c},{signal:s.signal});if(i==null)throw new Error("No DNS response received");return i}}function Hd(){return[Rl("https://cloudflare-dns.com/dns-query"),Rl("https://dns.google/resolve")]}var $d=hr(qd(),1);var Ml=class{lru;constructor(e){this.lru=(0,$d.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return wi({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??Dl)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function zd(r){return new Ml(r)}var zy=1e3,bi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=zd(e.cacheSize??zy),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["."]=Hd())}async query(e,t={}){let n=yi(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new de("dns:cache",{detail:s})),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??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 Gd(r={}){return new bi(r)}var xi=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-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(o*=e,o+=f,o>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wd=45,Gy=15,pn=new xi;function Ul(r){if(!(r.length>Gy))return pn.new(r).parseWith(()=>pn.readIPv4Addr())}function Ol(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wd))return pn.new(r).parseWith(()=>pn.readIPv6Addr())}function vi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wd))return pn.new(r).parseWith(()=>pn.readIPAddr())}var ES=parseInt("0xFFFF",16),AS=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ut(r){return!!Ul(r)}function mn(r){return!!Ol(r)}function Ei(r){return!!vi(r)}var Xd=ut,Yy=mn,Fl=function(r){let e=0;if(r=r.toString().trim(),Xd(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Yy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=Xd(t[n]),i;o&&(i=Fl(t[n]),t[n]=te(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,te(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 o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},Yd=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var gn={},Vl={},Qy=[[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"]];Qy.forEach(r=>{let e=ew(...r);Vl[e.code]=e,gn[e.name]=e});function ew(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function W(r){if(typeof r=="number"){if(Vl[r]!=null)return Vl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(gn[r]!=null)return gn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var i8=W("ip4"),a8=W("ip6"),c8=W("ipcidr");function $l(r,e){switch(W(r).code){case 4:case 41:return rw(e);case 42:return ql(e);case 43:return te(e,"base10");case 6:case 273:case 33:case 132:return ep(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ql(e);case 421:return iw(e);case 444:return Qd(e);case 445:return Qd(e);case 466:return ow(e);case 481:return globalThis.encodeURIComponent(ql(e));default:return te(e,"base16")}}function zl(r,e){switch(W(r).code){case 4:return Jd(e);case 41:return Jd(e);case 42:return Kl(e);case 43:return P(e,"base10");case 6:case 273:case 33:case 132:return Gl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Kl(e);case 421:return nw(e);case 444:return aw(e);case 445:return cw(e);case 466:return sw(e);case 481:return Kl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var Hl=Object.values(Gn).map(r=>r.decoder),tw=function(){let r=Hl[0].or(Hl[1]);return Hl.slice(2).forEach(e=>r=r.or(e)),r}();function Jd(r){if(!Ei(r))throw new Error("invalid ip address");return Fl(r)}function rw(r){let e=Yd(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ei(e))throw new Error("invalid ip address");return e}function Gl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function ep(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Kl(r){let e=P(r),t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function ql(r){let e=it(r);if(r=r.slice(pe(e)),r.length!==e)throw new Error("inconsistent lengths");return te(r)}function nw(r){let e;r[0]==="Q"||r[0]==="1"?e=rt(X.decode(`z${r}`)).bytes:e=me.parse(r).multihash.bytes;let t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function sw(r){let e=tw.decode(r),t=Uint8Array.from(ke(e.length));return Ve([t,e],t.length+e.length)}function ow(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+te(t,"base64url")}function iw(r){let e=it(r),t=r.slice(pe(e));if(t.length!==e)throw new Error("inconsistent lengths");return te(t,"base58btc")}function aw(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 s=Gl(n);return Ve([t,s],t.length+s.length)}function cw(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 s=Gl(n);return Ve([t,s],t.length+s.length)}function Qd(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=te(e,"base32"),s=ep(t);return`${n}:${s}`}function tp(r){r=Wl(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw np("invalid address: "+r);if(a.path===!0){n=Wl(s.slice(o).join("/")),e.push([a.code,zl(a.code,n)]),t.push([a.code,n]);break}let c=zl(a.code,s[o]);e.push([a.code,c]),t.push([a.code,$l(a.code,c)])}return{string:rp(t),bytes:Zl(e),tuples:e,stringTuples:t,path:n}}function jl(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=it(r,s),i=pe(o),a=W(o),c=lw(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let u=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw np("Invalid address Uint8Array: "+te(r,"base16"));e.push([o,u]);let f=$l(o,u);if(t.push([o,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:rp(t),tuples:e,stringTuples:t,path:n}}function rp(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Wl(e.join("/"))}function Zl(r){return Ve(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(ke(t.code));return e.length>1&&e[1]!=null&&(n=Ve([n,e[1]])),n}))}function lw(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 Wl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function np(r){return new Error("Error parsing address: "+r)}var uw=Symbol.for("nodejs.util.inspect.custom"),Yl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),fw=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Xl=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Ai=class r{bytes;#e;#t;#o;#a;[Yl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=jl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=tp(e)}else if(ar(e))t=jl(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.#o=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(o=`%${p??""}`),fw.includes(h)&&(t=i.name,s=443,n=`${p??""}${o}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,s=parseInt(p??"")),(h===c.code||h===u.code)&&(t=W(h).name,n=`${p??""}${o}`,e=h===u.code?6:4);if(e==null||t==null||n==null||s==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:s}}protos(){return this.#t.map(([e])=>Object.assign({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#o.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Zl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===gn.p2p.code&&e.push([n,s]),n===gn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?te(X.decode(`z${n}`),"base58btc"):te(me.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ue(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=yn.get(t.name);if(n==null)throw new Xl(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>j(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[uw](){return`Multiaddr(${this.#e})`}};var yn=new Map;function ar(r){return!!r?.[Yl]}function j(r){return new Ai(r)}var hw=32,{code:dw}=W("dnsaddr"),Jl=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},_r=async function(e,t={}){let n=t.maxRecursiveDepth??hw;if(n===0)throw new Jl("Max recursive depth reached");let[,s]=e.stringTuples().find(([u])=>u===dw)??[],i=await(t?.dns??Gd()).query(`_dnsaddr.${s}`,{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=j(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 hp=hr(fp(),1),Bi=hp.default;var bw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:_r}},transportManager:{faultTolerance:Kt.FATAL_ALL}};async function dp(r){let e=Bi(bw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return e}function xw(r,e){try{if(typeof r=="string"&&r.length>0)return vw(r);if(typeof r=="number"&&isFinite(r))return e?.long?Aw(r):Ew(r);throw new Error("Value is not a string or number.")}catch(t){let n=Sw(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function vw(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 Ii=xw;function Ew(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 Aw(r){let e=Math.abs(r);return e>=864e5?Ci(r,e,864e5,"day"):e>=36e5?Ci(r,e,36e5,"hour"):e>=6e4?Ci(r,e,6e4,"minute"):e>=1e3?Ci(r,e,1e3,"second"):`${r} ms`}function Ci(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function Sw(r){return typeof r=="object"&&r!==null&&"message"in r}function eu(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Ii,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 w=m,b=Number(new Date),y=b-(l||b);w.diff=y,w.prev=l,w.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 k=g[x];_=B.call(w,k),g.splice(x,1),x--}return _}),t.formatArgs.call(w,g),(w.log||t.log).apply(w,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 s(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 o(){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 ki=Lw(),_w=["#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 Bw(){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 Cw(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ii(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,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var Iw=console.debug??console.log??(()=>{});function kw(r){try{r?ki?.setItem("debug",r):ki?.removeItem("debug")}catch{}}function Tw(){let r;try{r=ki?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Lw(){try{return localStorage}catch{}}function Nw(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var pp=eu({formatArgs:Cw,save:kw,load:Tw,useColors:Bw,setupFormatters:Nw,colors:_w,storage:ki,log:Iw});var Ge=pp;Ge.formatters.b=r=>r==null?"undefined":X.baseEncode(r);Ge.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ge.formatters.m=r=>r==null?"undefined":zc.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":mp(r.stack)??mp(r.message)??r.toString();function Pw(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 Ti(){return{forComponent(r){return Dw(r)}}}function Dw(r){let e=Pw(`${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 mp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Br(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function Li(r){let e=rt(X.decode(`z${r}`));return dn(e)}var Ot=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 Br(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 Br(this.map.values(),e=>e.key)}values(){return Br(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Cr=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 Br(this.set.entries(),e=>{let t=Li(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Li(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Br(this.set.values(),e=>Li(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 xp=Symbol.for("@achingbrain/uint8arraylist");function bp(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Pi(r){return!!r?.[xp]}var we=class r{bufs;length;[xp]=!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(Pi(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(Pi(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=bp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=bp(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(Pi(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:s}=this._subList(e,t);return Ve(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ve(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=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(!Pi(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;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=Ce(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 s=fe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,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 s=fe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,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 s=fe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,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=Ce(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 s=fe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,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 s=fe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,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 s=fe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,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 s=fe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,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 s=fe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,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(!ue(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((s,o)=>s+o.byteLength,0)),n.length=t,n}};var tu=64,ft=class{fp;h;seed;constructor(e,t,n,s=2){if(s>tu)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=fe(s);for(let a=0;a<i.length;a++)i[a]=o[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?ue(this.fp,e.fp):!1}};function Ir(r,e){return Math.floor(Math.random()*(e-r))+r}var kr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ft))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 ft))throw new TypeError("Invalid Fingerprint");let t=Ir(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var ru={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},vp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ep=new globalThis.TextEncoder;function Rw(r,e){let t=ru[e],n=vp[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Mw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ru[e],s=vp[e],o=r;for(;o.length>0;){let i=Ep.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function nu(r,{size:e=32,utf8Buffer:t}={}){if(!ru[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 Mw(r,e,t);r=Ep.encode(r)}return Rw(r,e)}var Uw=hr(wp(),1);var bs={hash:r=>Number(nu(r,{size:32})),hashV:(r,e)=>Ow(bs.hash(r,e))};function Ow(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var Fw=500,xs=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??bs,this.seed=e.seed??Ir(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new kr(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new kr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Ir(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize));for(let a=0;a<Fw;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 kr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Vw={1:.5,2:.84,4:.95,8:.98};function Hw(r=.001){return r>.002?2:r>1e-5?4:8}function Ap(r,e=.001){let t=Hw(e),n=Vw[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),tu);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Di=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??bs,this.seed=e.seed??Ir(0,Math.pow(2,10)),this.filterSeries=[new xs({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 xs({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 vs(r,e=.001,t){return new Di({...Ap(r,e),...t??{}})}var Es;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.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)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:fe(0),payloadType:fe(0),payload:fe(0),signature:fe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(Es||(Es={}));var Ri=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var xn=class r{static createFromProtobuf=async e=>{let t=Es.decode(e),n=hn(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,s=e.codec,o=e.marshal(),i=Sp(n,s,o),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:s,payload:o,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ri("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Es.encode({publicKey:pt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ue(this.marshal(),e.marshal())}async validate(e){let t=Sp(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Sp=(r,e,t)=>{let n=P(r),s=ke(n.byteLength),o=ke(e.length),i=ke(t.length);return new we(s,n,o,e,i,t)};function _p(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var Bp="libp2p-peer-record",Cp=Uint8Array.from([3,1]);var As;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:fe(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let f=o.uint32();switch(f>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(f&7);break}}}return c})),s),n.encode=o=>Ue(o,n.codec()),n.decode=(o,i)=>Me(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:fe(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;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(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Ue(n,r.codec()),r.decode=(n,s)=>Me(n,r.codec(),s)})(As||(As={}));var Tr=class r{static createFromProtobuf=e=>{let t=As.decode(e),n=dn(rt(t.peerId)),s=(t.addresses??[]).map(i=>j(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=Bp;static CODEC=Cp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=As.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||!_p(this.multiaddrs,e.multiaddrs))}};function Kw(r){return r[Symbol.asyncIterator]!=null}function qw(r){if(Kw(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 Ss=qw;var cr={},vn=r=>{r.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)})};vn.addEventListener=(r,e)=>{cr[r]==null&&(cr[r]=[]),cr[r].push(e)};vn.removeEventListener=(r,e)=>{cr[r]!=null&&(cr[r]=cr[r].filter(t=>t===e))};vn.dispatchEvent=function(r,e,t){cr[r]!=null&&cr[r].forEach(n=>n(e,t))};var su=vn;var ou="lock:worker:request-read",iu="lock:worker:release-read",au="lock:master:grant-read",cu="lock:worker:request-write",lu="lock:worker:release-write",uu="lock:master:grant-write";var Ip=(r=21)=>Math.random().toString().substring(2);var kp=(r,e,t,n,s)=>(o,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()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(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&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)})}}}))},Tp=(r,e,t,n)=>async()=>{let s=Ip();return globalThis.postMessage({type:e,identifier:s,name:r}),new Promise(o=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===s&&(globalThis.removeEventListener("message",i),o(()=>{globalThis.postMessage({type:n,identifier:s,name:r})}))};globalThis.addEventListener("message",i)})},$w={singleProcess:!1},Lp=r=>{if(r=Object.assign({},$w,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return su.addEventListener("message",kp(t,"requestReadLock",ou,iu,au)),su.addEventListener("message",kp(t,"requestWriteLock",cu,lu,uu)),t}return{isWorker:!0,readLock:t=>Tp(t,ou,au,iu),writeLock:t=>Tp(t,cu,uu,lu)}};var Lr={},lr;async function fu(r,e){let t,n=new Promise(s=>{t=s});return r.add(async()=>gs((async()=>{await new Promise(s=>{t(()=>{s()})})})(),{milliseconds:e.timeout})),n}var zw=(r,e)=>{if(lr.isWorker===!0)return{readLock:lr.readLock(r,e),writeLock:lr.writeLock(r,e)};let t=new ir({concurrency:1}),n;return{async readLock(){if(n!=null)return fu(n,e);n=new ir({concurrency:e.concurrency,autoStart:!1});let s=n,o=fu(n,e);return t.add(async()=>{s.start(),await s.onIdle().then(()=>{n===s&&(n=null)})}),o},async writeLock(){return n=null,fu(t,e)}}},Gw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function hu(r){let e=Object.assign({},Gw,r);return lr==null&&(lr=Lp(e),lr.isWorker!==!0&&(lr.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),lr.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=zw(e.name,e)),Lr[e.name]}var En;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((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:fe(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})),o),s.encode=i=>Ue(i,s.codec()),s.decode=(i,a)=>Me(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((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),Ui.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=Ui.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),o),s.encode=i=>Ue(i,s.codec()),s.decode=(i,a)=>Me(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Mi.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');a.addresses.push(Mi.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Er('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Zn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Zn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{s.skipType(u&7);break}}}return a})),n),r.encode=s=>Ue(s,r.codec()),r.decode=(s,o)=>Me(s,r.codec(),o)})(En||(En={}));var Mi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.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)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:fe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(Mi||(Mi={}));var Ui;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.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)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Ue(t,r.codec()),r.decode=(t,n)=>Me(t,r.codec(),n)})(Ui||(Ui={}));function An(r,e){let t=En.decode(e);if(t.publicKey!=null&&r.publicKey==null){let o=hn(t.publicKey);r=kl(o)}let n=new Map,s=BigInt(Date.now());for(let[o,i]of t.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:o,isCertified:i})=>({multiaddr:j(o),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",Np=new TextEncoder().encode(Ft),Oi=Np[0],Nr=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]!==Oi)throw new Error("Invalid key")}toString(e="utf8"){return te(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Np),this._buf[0]!==Oi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Oi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Oi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return Ww(this.baseNamespace())}name(){return jw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Zw(e.map(t=>t.namespaces()))])}};function Ww(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function jw(r){let e=r.split(":");return e[e.length-1]}function Zw(r){return[].concat(...r)}var du="/peers/";function Sn(r){if(!Vs(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Nr(`${du}${e}`)}async function Pp(r,e,t){let n=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=j(s.multiaddr)),!ar(s.multiaddr))throw new R("Multiaddr was invalid");if(!await e(r,s.multiaddr))continue;let o=s.isCertified??!1,i=s.multiaddr.toString(),a=n.get(i);a!=null?s.isCertified=a.isCertified||o:n.set(i,{multiaddr:s.multiaddr,isCertified:o})}return[...n.values()].sort((s,o)=>s.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:s,multiaddr:o})=>({isCertified:s,multiaddr:o.bytes}))}async function Vi(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer;if(s!=null&&!r.equals(s.id))throw new R("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,u=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.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=Fi(d,{validate:Dp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Fi(d,{validate:Rp,map:Mp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.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=Fi([...a.entries()],{validate:Dp})}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=Fi([...h.entries()],{validate:Rp,map:Mp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;s?.id.publicKey!=null?f=pt(s.id.publicKey):e.publicKey!=null?f=pt(e.publicKey):r.publicKey!=null&&(f=pt(r.publicKey));let l={addresses:await Pp(r,n.addressFilter??(async()=>!0),o),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 Fi(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function Dp(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function Rp(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Mp(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 Hi(r,e){let t=r.toString().split("/")[2],n=me.parse(t,We),s=mi(n);return An(s,e)}function Xw(r){return r==null?{}:{prefix:du,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(Hi(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(Hi(t.key,t.value),Hi(n.key,n.value)))}}var Ki=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=hu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new R("Cannot delete self peer");await this.datastore.delete(Sn(e))}async load(e){let t=await this.datastore.get(Sn(e));return An(e,t)}async save(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Vi(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,s)}async patch(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Vi(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async merge(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Vi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Xw(e??{}))){let s=Hi(t,n);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Sn(e)),n=An(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,s){let o=En.encode(t);return n!=null&&ue(o,n)?{peer:An(e,o),previous:s,updated:!1}:(await this.datastore.put(Sn(e),o),{peer:An(e,o),previous:s,updated:!0})}};var pu=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 Ki(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 s of this.store.all(t))e(s)}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 Ss(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 s=await this.store.save(e,t);return this.#e(e,s),s.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 s=await this.store.patch(e,t);return this.#e(e,s),s.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 s=await this.store.merge(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await xn.openAndCertify(e,Tr.DOMAIN),s=mi(n.publicKey.toCID());if(t?.equals(s)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,s),!1;let o=Tr.createFromProtobuf(n.payload),i;try{i=await this.get(s)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await xn.createFromProtobuf(i.peerRecordEnvelope),c=Tr.createFromProtobuf(a.payload);if(c.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.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 Up(r,e={}){return new pu(r,e)}var qi=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 Yw(r){return r[Symbol.asyncIterator]!=null}function Jw(r){if(Yw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var mu=Jw;function Qw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Op=Qw;function eb(r){return r[Symbol.asyncIterator]!=null}function tb(r,e){let t=0;if(eb(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Op(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var Pr=tb;function rb(r){return r[Symbol.asyncIterator]!=null}function nb(r,e){return rb(r)?async function*(){yield*(await Ss(r)).sort(e)}():function*(){yield*Ss(r).sort(e)}()}var gu=nb;function sb(r){return r[Symbol.asyncIterator]!=null}function ob(r,e){return sb(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 yu=ob;var $i=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:s}of e)await this.put(n,s,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,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await mu(this.putMany(e,n)),e=[],await mu(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 s=e.prefix;n=Pr(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Pr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>gu(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=yu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Pr(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Pr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>gu(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=yu(n,e.limit)),n}};var zi=class extends $i{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 qi;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 Nr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Nr(e)}};function Fp(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Hp=hr(Vp(),1),ib=["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"],ab=ib.map(r=>new Hp.Netmask(r));function wu(r){for(let e of ab)if(e.contains(r))return!0;return!1}function cb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function lb(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"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return wu(s)}function ub(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function fb(r){let e=r.split(":"),t=e[e.length-1];return wu(t)}function hb(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 _n(r){return ut(r)?wu(r):cb(r)?lb(r):ub(r)?fb(r):mn(r)?hb(r):void 0}var Kp=864e13;var db=448,bu=449,pb=53,mb=54,gb=55,yb=56,Gi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=_n(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?Kp-Date.now():0,lastVerified:s?Kp-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[s,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",s,o.domain,new Error("where")),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:j(`/${o.map(f=>[W(f[0]).name,f[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===db&&e[n+1]?.[0]!==bu)return e.splice(n+1,0,[bu,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),s=s||i.verified,i.verified=!1,i.expires=Date.now()+t);return s}findHost(e){for(let t of e.stringTuples())if(t[0]===bu||t[0]===pb||t[0]===mb||t[0]===gb||t[0]===yb)return t[1]}};var xu=4,vu=41,Eu=6,wb=273,Wi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t[0][1])return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:ut(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",s=t[1][0]===Eu?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let u=0;u<c.length;u++){let f=c[u];f.externalIp===n&&f.externalPort===o&&f.protocol===s&&(this.log("removing %s:%s to %s:%s %s IP mapping",f.externalIp,f.externalPort,n,o,s),i=i||f.verified,c.splice(u,1),u--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let s=n.stringTuples(),o;if((s[0][0]===xu||s[0][0]===vu)&&s[1][0]===Eu?o=`${s[0][1]}-${s[1][1]}-tcp`:(s[0][0]===xu||s[0][0]===vu)&&s[1][0]===wb&&(o=`${s[0][1]}-${s[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)s[0][0]=a.externalFamily===4?xu:vu,s[0][1]=a.externalIp,s[1][1]=`${a.externalPort}`,t.push({multiaddr:j(`/${s.map(c=>[W(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let s=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===s&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),s=n[0][1]??"",o=n[1][0]===Eu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let u=0;u<c.length;u++){let f=c[u];f.externalIp===s&&f.externalPort===i&&f.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",f.externalIp,f.externalPort,s,i,o),a=a||f.verified,f.verified=!1,f.expires=Date.now()+t)}return a}};function qp(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}var bb=4,xb=41,vb=53,Eb=54,Ab=55,Sb=56;function Dr(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!0;if(e===vb||e===Eb||e===Ab||e===Sb)return!1;if(e===bb||e===xb)return _n(t)??!1}catch{}return!0}var _b={maxObservedAddresses:10},ji=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??_b.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Dr(e)||qp(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var Bb={maxObservedAddresses:10},Zi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??Bb.maxObservedAddresses}get(e,t){if(Dr(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!1,expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}};var $p=6e4,zp={maxObservedAddresses:10,addressVerificationTTL:$p*10,addressVerificationRetry:$p*5},Cb=r=>r;function Au(r,e){let t=r.getPeerId();return t!=null&&bt(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var Xi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new ji(e,t),this.dnsMappings=new Gi(e,t),this.ipMappings=new Wi(e,t),this.transportAddresses=new Zi(e,t),this.announceFilter=t.announceFilter??Cb,this.observedAddressFilter=vs(1024),this.addressVerificationTTL=t.addressVerificationTTL??zp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??zp.addressVerificationRetry,this._updatePeerStoreAddresses=Fp(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.getAddresses().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=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Au(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Au(e,this.components.peerId);let n=!0;this.observed.has(e)&&(n=this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)),this.transportAddresses.has(e)&&(n=this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)),this.dnsMappings.has(e)&&(n=this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),this.ipMappings.has(e)&&(n=this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Au(e,this.components.peerId);let n=!1;this.observed.has(e)&&(n=this.observed.remove(e)),this.transportAddresses.has(e)&&(n=this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.dnsMappings.has(e)&&(n=this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.ipMappings.has(e)&&(n=this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=j(n);return s.protos().pop()?.path===!0||s.getPeerId()===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${ut(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(j(`/ip${ut(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}};var Gp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Gp||(Gp={}));var Yi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Ji=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Bn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Bs=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"}},ea=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ta=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Cs=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Rr=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},ra=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},na=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Mr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Ur=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},sa=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Su=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=Ti())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Zs(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")}},kb=["metrics","connectionProtector","dns"],Tb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Wp(r={}){let e=new Su(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!Tb.includes(s)){let i=e.components[s];if(i==null&&!kb.includes(s))throw new Yi(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function jp(r){let e={};for(let t of Object.values(r.components))for(let n of Lb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Nb(t))if(e[n]!==!0)throw new Ji(`Service "${Pb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Lb(r){return Array.isArray(r?.[Rn])?r[Rn]:[]}function Nb(r){return Array.isArray(r?.[ec])?r[ec]:[]}function Pb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Db=r=>r.toString().split("/").slice(1),Cn=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),z=r=>({match:e=>Cn(t=>t===r).match(e),pattern:r}),Or=()=>({match:r=>Cn(e=>typeof e=="string").match(r),pattern:"{string}"}),Is=()=>({match:r=>Cn(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),re=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{X.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ks=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Gc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Pe=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),G=(...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 ce(...r){function e(s){let o=Db(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var ia=G(z("dns4"),Or()),aa=G(z("dns6"),Or()),ca=G(z("dnsaddr"),Or()),Bu=G(z("dns"),Or()),y4=ce(ia,Z(re())),w4=ce(aa,Z(re())),b4=ce(ca,Z(re())),x4=ce(Pe(Bu,ca,ia,aa),Z(re())),Zp=G(z("ip4"),Cn(ut)),Xp=G(z("ip6"),Cn(mn)),Cu=Pe(Zp,Xp),Vt=Pe(Cu,Bu,ia,aa,ca),v4=ce(Pe(Cu,G(Pe(Bu,ca,ia,aa),Z(re())))),E4=ce(Zp),A4=ce(Xp),S4=ce(Cu),Iu=G(Vt,z("tcp"),Is()),Ts=G(Vt,z("udp"),Is()),ku=ce(G(Iu,Z(re()))),_4=ce(Ts),Tu=G(Ts,z("quic"),Z(re())),la=G(Ts,z("quic-v1"),Z(re())),Rb=Pe(Tu,la),B4=ce(Tu),C4=ce(la),_u=Pe(Vt,Iu,Ts,Tu,la),Yp=Pe(G(_u,z("ws"),Z(re()))),Ls=ce(Yp),Jp=Pe(G(_u,z("wss"),Z(re())),G(_u,z("tls"),Z(G(z("sni"),Or())),z("ws"),Z(re()))),Lu=ce(Jp),Qp=G(Ts,z("webrtc-direct"),Z(ks()),Z(ks()),Z(re())),Nu=ce(Qp),em=G(la,z("webtransport"),Z(ks()),Z(ks()),Z(re())),Pu=ce(em),oa=Pe(Yp,Jp,G(Iu,Z(re())),G(Rb,Z(re())),G(Vt,Z(re())),Qp,em,re()),I4=ce(oa),Mb=G(oa,z("p2p-circuit"),re()),Ns=ce(Mb),Ub=Pe(G(oa,z("p2p-circuit"),z("webrtc"),Z(re())),G(oa,z("webrtc"),Z(re())),G(z("webrtc"),Z(re()))),Du=ce(Ub),Ob=Pe(G(Vt,z("tcp"),Is(),z("http"),Z(re())),G(Vt,z("http"),Z(re()))),k4=ce(Ob),Fb=Pe(G(Vt,z("tcp"),Pe(G(z("443"),z("http")),G(Is(),z("https"))),Z(re())),G(Vt,z("tls"),z("http"),Z(re())),G(Vt,z("https"),Z(re()))),T4=ce(Fb),Vb=Pe(G(z("memory"),Or(),Z(re()))),L4=ce(Vb);var Hb=4,Kb=41;function tm(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Ls.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Hb||t[0][0]===Kb?!!_n(`${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 rm=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},qb=new WeakMap;function $b({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(rm());let o,i,a,c=r??clearTimeout,u=()=>{c(o),a(rm())},f=()=>{s&&s.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",u,{once:!0}),qb.set(l,()=>{c(o),o=null,i()}),l}}var zb=$b(),nm=zb;var ua=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}},fa=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ha=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 Ru}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);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(s,i.consumedPoints,this.blockDuration)),new ua("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 nm(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,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)}},Ru=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,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 da(r){if(Vs(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:bt(t),r.forEach(n=>{if(!ar(n))throw new qt("Invalid multiaddr");let s=n.getPeerId();if(s==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let o=bt(s);if(e?.equals(o)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Gb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sm(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??Gb;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}var om="last-dial-failure",im="last-dial-success";var pa=100,ma=50;var am={maxConnections:pa,allow:[]},ga=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??am.maxConnections,this.allow=t.allow??am.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){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 Ot;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 s=this.sortConnections(e,n),o=Math.max(t-this.maxConnections,0),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===o)break;await Promise.all(i.map(async a=>{await sm(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};function he(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ya=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}},In=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ya(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 ya(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 Mu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function wa(r={}){return Wb(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 Wb(r,e){e=e??{};let t=e.onEnd,n=new In,s,o,i,a=he(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,w)=>{o=b=>{o=null,n.push(b);try{g(r(n))}catch(y){w(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=he()})}},u=g=>o!=null?o(g):(n.push(g),s),f=g=>(n=new In,o!=null?o({error:g}):(n.push({error:g}),s)),l=g=>{if(i)return s;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?s:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new In,d(),{done:!0}),p=g=>(d(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let w=g?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,y;w!=null&&(b=new Promise((x,A)=>{y=()=>{A(new Mu)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,b])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},t==null)return s;let m=s;return s={[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),s},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},s}var Uu=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 kn(r,e,t,n){let s=new Uu(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((o,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(),o(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(s)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ba=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 ur(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ba(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new ba(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var xa=class{deferred;signal;constructor(e){this.signal=e,this.deferred=he(),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 jb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var va=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=jb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,se(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 xa(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 ur(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 Tn=class extends Et{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new fa;let n=new va(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}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 kn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await kn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await kn(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=wa({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new et("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ea=class extends Tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ht(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function Zb(r,e){let t=ku.exactMatch(r.multiaddr),n=ku.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Lu.exactMatch(r.multiaddr),o=Lu.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Ls.exactMatch(r.multiaddr),a=Ls.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Du.exactMatch(r.multiaddr),u=Du.exactMatch(e.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=Nu.exactMatch(r.multiaddr),l=Nu.exactMatch(e.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=Pu.exactMatch(r.multiaddr),h=Pu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Xb(r,e){let t=Dr(r.multiaddr),n=Dr(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Yb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Jb(r,e){let t=Ns.exactMatch(r.multiaddr),n=Ns.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function cm(r){return r.sort(Zb).sort(Yb).sort(Jb).sort(Xb)}async function lm(r,e){let t=!1;for(let s of yn.keys())if(t=r.protoNames().includes(s),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(s=>s.toString())),n}var Aa={maxParallelDials:ma,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:_r}},Sa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Aa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Aa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Aa.dialTimeout,this.connections=t.connections??new Ot,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,se(1/0,this.shutDownController.signal);for(let[n,s]of Object.entries(t.resolvers??{}))yn.set(n,s);this.queue=new Ea({concurrency:t.maxParallelDials??Aa.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,se(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=da(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:s.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),o;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 s)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 s)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 zr("Dial queue is full");return this.log("creating dial target for %p",n,s.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=Ht([this.shutDownController.signal,a.signal]);se(1/0,c);let 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 zr("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:{[im]: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:{[om]: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 Gs(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??Hu,multiaddrs:new Set(s.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(l=>({multiaddr:j(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new zr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Cs("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);s.push(...l.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(s.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,s.map(({multiaddr:d})=>d.toString())),s.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 o=(await Promise.all(s.map(async l=>{let d=await lm(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()}`;o=o.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=o.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 Rr("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=this.addressSorter==null?cm(u):u.sort(this.addressSorter);if(f.length===0)throw new Cs("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr: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(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!Ns.matches(s.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var _a=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gm=hr(pm(),1);var ex=Object.prototype.toString,tx=r=>ex.call(r)==="[object Error]",rx=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 Ku(r){return r&&tx(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:rx.has(r.message):!1}var qu=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}},mm=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function $u(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=gm.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.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 qu)throw c.originalError;if(c instanceof TypeError&&!Ku(c))throw c;if(mm(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(u){mm(u,a,e),i(),n(u)}}})})}var Ba=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new _a({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);ym(t)&&(this.queue.has(e)||this.queue.add(async n=>{await $u(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(Qa)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>ym(t)]});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()}};function ym(r){for(let e of r.tags.keys())if(e.startsWith(Qa))return!0;return!1}var Hu=50,zu={maxConnections:pa,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ca=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??zu.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Ot,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>j(n)),this.deny=(t.deny??[]).map(n=>j(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??zu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ha({points:t.inboundConnectionThreshold??zu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ga({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Sa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ma,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:_r},connections:this.connections}),this.reconnectQueue=new Ba({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;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 s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??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 s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await df(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await pf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(s){this.log.error(s)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}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}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),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,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),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.started)throw new vt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=da(e);if(this.peerId.equals(n))throw new $r("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 s=await this.dialQueue.dial(e,{...t,priority:t.priority??Hu});if(s.status!=="open")throw new qr("Remote closed connection during opening");let o=this.connections.get(s.remotePeer);o==null&&(o=[],this.connections.set(s.remotePeer,o));let i=!1;for(let a of o)if(a.id===s.id&&(i=!0),t.force!==!0&&a.id!==s.id&&a.remoteAddr.equals(s.remoteAddr))return s.abort(new qt("Duplicate multiaddr connection")),a;return i||o.push(s),s}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await s.close(t)}catch(o){s.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(s=>e.remoteAddr.toString().startsWith(s.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>e.remoteAddr.toString().startsWith(s.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 s=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(s,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s),!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=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Ln=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),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var ox=1.2,ix=2,ax=2e3,Ia=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Ln(e.interval??5e3),this.failure=new Ln(e.interval??5e3),this.next=new Ln(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??ix,this.timeoutMultiplier=e.timeoutMultiplier??ox,this.minTimeout=e.minTimeout??ax,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),s=Ht([e.signal,n]);return se(1/0,s,n),s.start=Date.now(),s.timeout=t,s}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 Gu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=he(),this.haveNext=he()}[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=he(),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=he(),await ur(this.readNext.promise,t?.signal,t)}};function wm(){return new Gu}var ka=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Wu=class extends Error{code;constructor(e,t){super(e),this.code=t}},ju=class extends Wu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ta(r,e){let t=wm();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 s=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new ju("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 we:d}for(;s.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new ka("unexpected end of input");s.append(l)}let f=s.sublist(0,i);return s.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(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var cx=1e4,lx="1.0.0",ux="ping",fx="ipfs",bm=32,hx=!0,La=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??fx}/${ux}/${lx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??cx,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??hx,this.timeout=new Ia({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Rn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,se(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}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Ta(s);t=Date.now(),await Promise.all([o.write(un(bm),{signal:n}),o.read(bm,{signal:n})]),e.rtt=Date.now()-t,await o.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 dx(r){return r[Symbol.asyncIterator]!=null}function px(...r){let e=[];for(let t of r)dx(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=wa({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Ps=px;var Na=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 Bn("No content routers available");let n=this,s=new Cr;for await(let o of Ps(...n.routers.map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new vt;await Promise.all(this.routers.map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new vt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Pa=globalThis.CustomEvent??Event;async function*Zu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=he(),a=he(),c=!1,u,f=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=he(),await i.promise),f)break;let m={done:!1};o.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,s.dispatchEvent(new Pa("task-complete"))},g=>{m.done=!0,m.err=g,s.dispatchEvent(new Pa("task-complete"))})}c=!0,s.dispatchEvent(new Pa("task-complete"))}catch(p){u=p,s.dispatchEvent(new Pa("task-complete"))}});function l(){return n?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.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<o.length;p++)if(o[p].done){let m=o[p];if(o.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=he(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&o.length===0)break}}var Da=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 Bs("No peer routers available");if(e.toString()===this.peerId.toString())throw new Qi("Should not try to find self");let n=this,s=Ps(...this.routers.map(o=>async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new Ks}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Bs("No peer routers available");let n=this,s=vs(1024);for await(let o of Zu(async function*(){let i=Ps(...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}}()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var Ra=class extends Et{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,se(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,se(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ht([this.shutdownController.signal,e?.signal]);se(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=he(),yield(await kn(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,se(1/0,this.walkController.signal);let e=Ht([this.walkController.signal,this.shutdownController.signal]);se(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=un(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ur(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("randomwalk errored",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("randomwalk errored",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Xu=32,Yu=64,Ma=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 ea(`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 ta(`Handler already registered for protocol ${e}`);let s=Bi.bind({ignoreUndefined:!0})({maxInboundStreams:Xu,maxOutboundStreams:Yu},n);this.handlers.set(e,{handler:t,options:s}),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 R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.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 s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let i of o.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,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of s){let i=this.topologies.get(o);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,s=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),a.onConnect?.(s,n))}}};var Ju=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 xm(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ju({name:e,metrics:t}):n=new Map,n}var Ua=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=xm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Kt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`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 s=n.pop();s!=null&&e.push(s.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 sa(`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 vt("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,s]of this.transports.entries()){let o=s.listenFilter(e),i=[];for(let u of o){this.log("creating listener for %s on %a",n,u);let f=s.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!==Kt.NO_FATAL)throw new Rr(`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===Kt.FATAL_ALL)throw new Rr(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 s=t.pop();s!=null&&n.push(s.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 _e="/multistream/1.0.0";var Oa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Fa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Va=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ds(r,e={}){let t=Ta(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=pe(e.maxDataLength));let n=e?.lengthDecoder??it,s=e?.lengthEncoder??ke;return{read:async i=>{let a=-1,c=new we;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 Oa("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Va("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Fa("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[s(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var mx=P(`
|
|
7
|
+
`);async function Vr(r,e,t){await r.write(e,t)}async function vm(r,e,t){await r.writeV(e,t)}async function gx(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==mx[0])throw e.log.error("Invalid mss message - missing newline",t),new zs("Missing newline");return t.sublist(0,-1)}async function fr(r,e){let t=await gx(r,e);return te(t.subarray())}async function Rs(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return yx(r,e[0],t);let n=Ds(r,{...t,maxDataLength:1024}),s=e.shift();if(s==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',_e,s);let o=P(`${_e}
|
|
8
|
+
`),i=P(`${s}
|
|
9
|
+
`);await vm(n,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await fr(n,t);if(t.log.trace('select: read "%s"',a),a===_e&&(t.log.trace("select: reading protocol response"),a=await fr(n,t),t.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(let c of e){t.log.trace('select: write "%s"',c),await Vr(n,P(`${c}
|
|
10
|
+
`),t),t.log.trace("select: reading protocol response");let u=await fr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new Dn("protocol selection failed")}function yx(r,e,t){let n=r.sink.bind(r),s=r.source,o=!1,i=!1,a=he(),c=!1,u=!1,f=he(),l=!1,d=!1,h=he(),p=Ds({sink:n,source:s},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:y}=p.unwrap();await y(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',_e,e,A.byteLength);let _=`${e}
|
|
11
11
|
`;yield new we(Uint8Array.from([19]),P(`${_e}
|
|
12
|
-
`),ke(_.length),P(_),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',_e,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 w())}finally{i=!1,
|
|
12
|
+
`),ke(_.length),P(_),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',_e,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 w())}finally{i=!1,o=!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',_e,e),await p.writeV([P(`${_e}
|
|
13
13
|
`),P(`${e}
|
|
14
|
-
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',_e,e)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await fr(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===_e&&(b=await fr(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new
|
|
15
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',_e,
|
|
16
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',
|
|
14
|
+
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',_e,e)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await fr(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===_e&&(b=await fr(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new Dn("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 y=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await b(y)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async y=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await b(y)}}if(r.close!=null){let b=r.close.bind(r);r.close=async y=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await ur(Promise.all(x),y?.signal):(o=!0,i=!1,a.resolve()),await b(y)}}return{stream:r,protocol:e}}function Ha(r){return r[Symbol.asyncIterator]!=null}var Ka=r=>{let e=pe(r),t=Ce(e);return ke(r,t),Ka.bytes=e,t};Ka.bytes=0;function qa(r,e){e=e??{};let t=e.lengthEncoder??Ka;function*n(s){let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return Ha(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}qa.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ka;return new we(t(r.byteLength),r)};var $a=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},za=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ga=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ms=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var wx=8,bx=1024*1024*4,Hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Hr||(Hr={}));var tf=r=>{let e=it(r);return tf.bytes=pe(e),e};tf.bytes=0;function ef(r,e){let t=new we,n=Hr.LENGTH,s=-1,o=e?.lengthDecoder??tf,i=e?.maxLengthLength??wx,a=e?.maxDataLength??bx;function*c(){for(;t.byteLength>0;){if(n===Hr.LENGTH)try{if(s=o(t),s<0)throw new $a("Invalid message length");if(s>a)throw new za("Message length too long");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(s),n=Hr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ga("Message length length too long");break}throw u}if(n===Hr.DATA){if(t.byteLength<s)break;let u=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(u),yield u,n=Hr.LENGTH}}}return Ha(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Ms("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Ms("Unexpected end of input")}()}ef.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return ef(n,{...e??{},onLength:o=>{t=o}})};async function Us(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Ds(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let s=await fr(n,t);if(t.log.trace('handle: read "%s"',s),s===_e){t.log.trace('handle: respond with "%s" for "%s"',_e,s),await Vr(n,P(`${_e}
|
|
15
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',_e,s);continue}if(e.includes(s))return t.log.trace('handle: respond with "%s" for "%s"',s,s),await Vr(n,P(`${s}
|
|
16
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',s,s),{stream:n.unwrap(),protocol:s};if(s==="ls"){let o=new we(...e.map(i=>qa.single(P(`${i}
|
|
17
17
|
`))),P(`
|
|
18
|
-
`));t.log.trace('handle: respond with "%s" for %s',e,
|
|
19
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var cx=500,Xu=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";[sf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Fo("the connection is being closed");if(this.status==="closed")throw new Kr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new zr("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(cx);oe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function dm(r){return new Xu(r)}function fx(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return $u}function hx(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??zu}function pm(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var qa=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 Yi(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Ji("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{n&&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=wt(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=Vt([u,n.signal]);oe(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 Kt(`${t} connection that skipped encryption must have a peer id`);let h=wt(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new qr("Can not dial self");throw e.abort(d),d}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}finally{f.clear()}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);oe(1/0,g);let{stream:w,protocol:b}=await Ro(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let y=fx(b,this.components.registrar);if(pm(b,"inbound",l)===y){let A=new zo(`Too many inbound protocol streams for protocol "${b}" - limit ${y}`);throw p.abort(A),A}p.source=w.source,p.sink=w.sink,p.protocol=b,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.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 Rr("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);oe(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:b}=await Po(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",b);let y=hx(b,this.components.registrar,m),x=pm(b,"outbound",l);if(x>=y){let A=new Go(`Too many outbound protocol streams for protocol "${b}" - ${x}/${y}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=w.source,g.sink=w.sink,g.protocol=b,w.closeWrite!=null&&(g.closeWrite=w.closeWrite),w.closeRead!=null&&(g.closeRead=w.closeRead),w.close!=null&&(g.close=w.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(w){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,w),g.timeline.close==null&&g.abort(w),w}},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)=>(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 %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new Rr("Connection is not multiplexed")};return l=dm({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?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=d,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 zr("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 Ro(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Mr(`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 Mr(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 Po(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Mr(`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 Mr(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 Po(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 Rr(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 Ro(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 Rr(String(s))}}};var mm="2.3.1-06f79b646",gm="js-libp2p";var $a=class extends vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new vt,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},oe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ci(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Rp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:gm,version:mm},logger:this.logger,events:t,datastore:e.datastore??new Ki,connectionGater:zp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Lp(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 qa(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 Pa(this.components,e.transportManager)),this.configureComponent("connectionManager",new Aa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ca(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Na(this.components)),this.configureComponent("addressManager",new zi(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 Ta(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 Ia(this.components,{routers:i})),this.configureComponent("randomWalk",new La(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[Ga]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Ga])),u[ja]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ja])),u[Wa]!=null&&(this.log("registering service %s for peer discovery",a),u[Wa].addEventListener?.("peer",f=>{this.#e(f)}))}Mp(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 Cr;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 R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("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={}){ar(e)&&(e=wt(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=Ve([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=fn(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 px(r={}){r.privateKey??=await Bd("Ed25519");let e=new $a({...await ap(r),peerId:Td(r.privateKey)});return r.start!==!1&&await e.start(),e}return Tm(mx);})();
|
|
18
|
+
`));t.log.trace('handle: respond with "%s" for %s',e,s),await Vr(n,o,t),t.log.trace('handle: responded with "%s" for %s',e,s);continue}t.log.trace('handle: respond with "na" for "%s"',s),await Vr(n,P(`na
|
|
19
|
+
`),t),t.log('handle: responded with "na" for "%s"',s)}}var vx=500,rf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,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=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[hf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Hs("the connection is being closed");if(this.status==="closed")throw new qr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Gr("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(vx);se(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function Am(r){return new rf(r)}function Sx(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Xu}function _x(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??Yu}function Sm(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Wa=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 ra(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new na("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(s){throw this.metrics.errors?.increment({inbound:!0}),s}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;return n!=null&&(s=bt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ht([u,n.signal]);se(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(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new de(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new qt(`${t} connection that skipped encryption must have a peer id`);let h=bt(d);c="native",o=h}if(o.equals(this.components.peerId)){let d=new $r("Can not dial self");throw e.abort(d),d}if(i=s,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,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},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}finally{f.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,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);se(1/0,g);let{stream:w,protocol:b}=await Us(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let y=Sx(b,this.components.registrar);if(Sm(b,"inbound",l)===y){let A=new Ws(`Too many inbound protocol streams for protocol "${b}" - limit ${y}`);throw p.abort(A),A}p.source=w.source,p.sink=w.sink,p.protocol=b,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.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 Mr("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);se(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:b}=await Rs(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",b);let y=_x(b,this.components.registrar,m),x=Sm(b,"outbound",l);if(x>=y){let A=new js(`Too many outbound protocol streams for protocol "${b}" - ${x}/${y}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=w.source,g.sink=w.sink,g.protocol=b,w.closeWrite!=null&&(g.closeWrite=w.closeWrite),w.closeRead!=null&&(g.closeRead=w.closeRead),w.close!=null&&(g.close=w.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(w){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,w),g.timeline.close==null&&g.abort(w),w}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer - %e",p)}));let d=s.timeline;s.timeline=new Proxy(d,{set:(...p)=>(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 %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),s.timeline.upgraded=Date.now();let h=()=>{throw new Mr("Connection is not multiplexed")};return l=Am({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await s.close(p)},abort:p=>{s.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=d,l}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Gr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await Us(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Ur(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Ur(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Rs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Ur(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Ur(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Rs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Mr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await Us(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Mr(String(o))}}};var _m="2.3.1-2625cc323",Bm="js-libp2p";var ja=class extends Et{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Et,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},se(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ti(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=this.components=Wp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Bm,version:_m},logger:this.logger,events:t,datastore:e.datastore??new zi,connectionGater:tm(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Up(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),s.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)};s.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new Wa(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 Ua(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ca(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new La(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ma(this.components)),this.configureComponent("addressManager",new Xi(this.components,e.addresses));let o=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Da(this.components,{routers:o}));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 Na(this.components,{routers:i})),this.configureComponent("randomWalk",new Ra(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[Xa]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Xa])),u[Ja]!=null&&(this.log("registering service %s for peer routing",a),o.push(u[Ja])),u[Ya]!=null&&(this.log("registering service %s for peer discovery",a),u[Ya].addEventListener?.("peer",f=>{this.#e(f)}))}jp(s)}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 Cr;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 R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("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={}){ar(e)&&(e=bt(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=Ve([P("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=hn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,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 Cx(r={}){r.privateKey??=await Nd("Ed25519");let e=new ja({...await dp(r),peerId:Md(r.privateKey)});return r.start!==!1&&await e.start(),e}return Vm(Ix);})();
|
|
20
20
|
/*! Bundled license information:
|
|
21
21
|
|
|
22
22
|
pvtsutils/build/index.js:
|