libp2p 2.3.1-339b7df88 → 2.3.1-406b3916c
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 +10 -10
- package/dist/src/address-manager.d.ts.map +1 -1
- package/dist/src/address-manager.js +31 -9
- package/dist/src/address-manager.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +11 -10
- package/src/address-manager.ts +43 -10
- package/src/version.ts +1 -1
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 Qt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Dt=(r,t)=>{for(var e in t)Mo(r,e,{get:t[e],enumerable:!0})},of=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cm(t))!km.call(r,o)&&o!==e&&Mo(r,o,{get:()=>t[o],enumerable:!(n=Bm(t,o))||n.enumerable});return r};var fr=(r,t,e)=>(e=r!=null?_m(Im(r)):{},of(t||!r||!r.__esModule?Mo(e,"default",{value:r,enumerable:!0}):e,r)),Tm=r=>of(Mo({},"__esModule",{value:!0}),r);var mh=Qt(rn=>{"use strict";var ry="[object ArrayBuffer]",ke=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===ry}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},al="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(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=ke.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Xt=class{static toString(t,e=!1){let n=ke.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},xs=class r{static isHex(t){return typeof t===al&&ny.test(t)}static isBase64(t){return typeof t===al&&oy.test(t)}static isBase64Url(t){return typeof t===al&&sy.test(t)}static ToString(t,e="utf8"){let n=ke.toUint8Array(t);switch(e.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Xt.toString(n,!0);case"utf16":case"utf16be":return Xt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Xt.fromString(t,!0);case"utf16":case"utf16be":return Xt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=ke.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return bs.fromString(t);case"utf16":case"utf16be":return Xt.fromString(t);case"utf16le":case"usc2":return Xt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return bs.toString(t);case"utf16":case"utf16be":return Xt.toString(t);case"utf16le":case"usc2":return Xt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=ke.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=ke.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Xt.toString(t,e)}static FromUtf16String(t,e=!1){return Xt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};xs.DEFAULT_UTF8_ENCODING="utf8";function iy(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function ay(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function cy(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}rn.BufferSourceConverter=ke;rn.Convert=xs;rn.assign=iy;rn.combine=ay;rn.isEqual=cy});var Nd=Qt((bA,Sl)=>{"use strict";var Ny=Object.prototype.hasOwnProperty,Ht="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(Ht=!1));function Py(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Ld(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Py(e,n||r,o),i=Ht?Ht+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function di(r,t){--r._eventsCount===0?r._events=new ho:delete r._events[t]}function Nt(){this._events=new ho,this._eventsCount=0}Nt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Ny.call(e,n)&&t.push(Ht?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Nt.prototype.listeners=function(t){var e=Ht?Ht+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Nt.prototype.listenerCount=function(t){var e=Ht?Ht+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(t,e,n,o,s,i){var a=Ht?Ht+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,n);break;case 4:c[l].fn.call(c[l].context,e,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Nt.prototype.on=function(t,e,n){return Ld(this,t,e,n,!1)};Nt.prototype.once=function(t,e,n){return Ld(this,t,e,n,!0)};Nt.prototype.removeListener=function(t,e,n,o){var s=Ht?Ht+t:t;if(!this._events[s])return this;if(!e)return di(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!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!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:di(this,s)}return this};Nt.prototype.removeAllListeners=function(t){var e;return t?(e=Ht?Ht+t:t,this._events[e]&&di(this,e)):(this._events=new ho,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=Ht;Nt.EventEmitter=Nt;typeof Sl<"u"&&(Sl.exports=Nt)});var Ud=Qt((KA,Md)=>{Md.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Qd=Qt((S8,Jd)=>{"use strict";Jd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var sp=Qt((np,op)=>{"use strict";var vi=Qd(),{hasOwnProperty:ep}=Object.prototype,{propertyIsEnumerable:ow}=Object,yn=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),sw=np,tp={concatArrays:!1,ignoreUndefined:!1},Ei=r=>{let t=[];for(let e in r)ep.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)ow.call(r,n)&&t.push(n)}return t};function wn(r){return Array.isArray(r)?iw(r):vi(r)?aw(r):r}function iw(r){let t=r.slice(0,0);return Ei(r).forEach(e=>{yn(t,e,wn(r[e]))}),t}function aw(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ei(r).forEach(e=>{yn(t,e,wn(r[e]))}),t}var rp=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?yn(r,o,Wl(r[o],t[o],n)):yn(r,o,wn(t[o])))}),r),cw=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)ep.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)),e)}),n};function Wl(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?cw(r,t,e):!vi(t)||!vi(r)?wn(t):rp(r,t,Ei(t),e)}op.exports=function(...r){let t=Wl(wn(tp),this!==sw&&this||{},tp),e={_:{}};for(let n of r)if(n!==void 0){if(!vi(n))throw new TypeError("`"+n+"` is not an Option Object");e=Wl(e,{_:n},t)}return e._}});var up=Qt((yo,ki)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%4,g=h.length-m,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},e.x86.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,w=p,b=p,y=p,x=p,A=0,_=0,v=0,B=0,k=597399067,Y=2869860233,H=951274213,V=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,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[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,V),B=s(B,18),B=o(B,k),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,H),v=s(v,17),v=o(v,V),y^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,Y),_=s(_,16),_=o(_,H),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,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)},e.x64.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,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=e),yo.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(yo)});var hp=Qt((J8,fp)=>{fp.exports=up()});var Up=Qt(_o=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+e(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),_o.ip2long=i,_o.long2ip=a,_o.Netmask=r}).call(_o)});var em=Qt((h4,tm)=>{function Jt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}tm.exports=Jt;Jt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Jt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Jt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Jt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Jt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Jt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Jt.prototype.start=Jt.prototype.try;Jt.prototype.errors=function(){return this._errors};Jt.prototype.attempts=function(){return this._attempts};Jt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var rm=Qt(Ur=>{var Fb=em();Ur.operation=function(r){var t=Ur.timeouts(r);return new Fb(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ur.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Ur.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Ur.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Ur.operation(t),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=t}}});var om=Qt((p4,nm)=>{nm.exports=rm()});var px={};Dt(px,{createLibp2p:()=>dx});var sf=Symbol.for("@libp2p/connection");var $a=Symbol.for("@libp2p/content-routing");var za=Symbol.for("@libp2p/peer-discovery");var Uo=Symbol.for("@libp2p/peer-id");function Oo(r){return!!r?.[Uo]}var Ga=Symbol.for("@libp2p/peer-routing");var Wa="keep-alive";var Ex=Symbol.for("@libp2p/transport");var He;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(He||(He={}));var te=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var D=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},Ln=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Fo=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Hr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Vo=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Kr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Ke=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Ho=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ko=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Nn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},qo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var $o=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},xe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var qr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var $r=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},zo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Go=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},qe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var ot=(r,...t)=>{try{[...t]}catch{}};var ve=class extends EventTarget{#t=new Map;constructor(){super(),ot(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Wo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function af(...r){let t=[];for(let e of r)Wo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function cf(...r){let t=[];for(let e of r)Wo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Pn=Symbol.for("@libp2p/service-capabilities"),ja=Symbol.for("@libp2p/service-dependencies");var Qa={};Dt(Qa,{base58btc:()=>Z,base58flickr:()=>Mm});var Jx=new Uint8Array(0);function lf(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function uf(r){return new TextEncoder().encode(r)}function ff(r){return new TextDecoder().decode(r)}function Lm(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,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=e[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-${t} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Nm=Lm,Pm=Nm,df=Pm;var Za=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Xa=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return pf(this,t)}},Ya=class{decoders;constructor(t){this.decoders=t}or(t){return pf(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function pf(r,t){return new Ya({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ja=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Za(t,e,n),this.decoder=new Xa(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function zr({name:r,prefix:t,encode:e,decode:n}){return new Ja(r,t,e,n)}function $e({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=df(e,r);return zr({prefix:t,name:r,encode:n,decode:s=>Ee(o(s))})}function Rm(r,t,e,n){let o={};for(let f=0;f<t.length;++f)o[t[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|l,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Dm(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return zr({prefix:t,name:r,encode(o){return Dm(o,n,e)},decode(o){return Rm(o,n,e,r)}})}var Z=$e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mm=$e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tc={};Dt(tc,{base32:()=>Wt,base32hex:()=>Vm,base32hexpad:()=>Km,base32hexpadupper:()=>qm,base32hexupper:()=>Hm,base32pad:()=>Om,base32padupper:()=>Fm,base32upper:()=>Um,base32z:()=>$m});var Wt=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Um=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Om=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fm=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vm=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hm=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Km=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qm=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$m=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ec={};Dt(ec,{base36:()=>Rn,base36upper:()=>zm});var Rn=$e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zm=$e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gm=yf,mf=128,Wm=127,jm=~Wm,Zm=Math.pow(2,31);function yf(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Zm;)t[e++]=r&255|mf,r/=128;for(;r&jm;)t[e++]=r&255|mf,r>>>=7;return t[e]=r|0,yf.bytes=e-n+1,t}var Xm=rc,Ym=128,gf=127;function rc(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw rc.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&gf)<<o:(i&gf)*Math.pow(2,o),o+=7}while(i>=Ym);return rc.bytes=s-n,e}var Jm=Math.pow(2,7),Qm=Math.pow(2,14),tg=Math.pow(2,21),eg=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<tg?3:r<eg?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,Dn=lg;function Mn(r,t=0){return[Dn.decode(r,t),Dn.decode.bytes]}function Gr(r,t,e=0){return Dn.encode(r,t,e),t}function Wr(r){return Dn.encodingLength(r)}function ee(r,t){let e=t.byteLength,n=Wr(r),o=n+Wr(e),s=new Uint8Array(o+e);return Gr(r,s,0),Gr(e,s,n),s.set(t,o),new jr(r,e,t,s)}function re(r){let t=Ee(r),[e,n]=Mn(t),[o,s]=Mn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new jr(e,o,i,t)}function wf(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&lf(r.bytes,e.bytes)}}var jr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function bf(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return fg(e,nc(r),t??Z.encoder);default:return hg(e,nc(r),t??Wt.encoder)}}var xf=new WeakMap;function nc(r){let t=xf.get(r);if(t==null){let e=new Map;return xf.set(r,e),e}return t}var mt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==dg)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=ee(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&wf(t.multihash,n.multihash)}toString(t){return bf(this,t)}toJSON(){return{"/":bf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??vf(n,o,s.bytes))}else if(e[pg]===!0){let{version:n,multihash:o,code:s}=e,i=re(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Un)throw new Error(`Version 0 CID must use dag-pb (code: ${Un}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=vf(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Un,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new jr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=Mn(t.subarray(e));return e+=d,l},o=n(),s=Un;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=ug(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return nc(s).set(n,t),s}};function ug(r,t){switch(r[0]){case"Q":{let e=t??Z;return[Z.prefix,e.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}case Wt.prefix:{let e=t??Wt;return[Wt.prefix,e.decode(r)]}case Rn.prefix:{let e=t??Rn;return[Rn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function fg(r,t,e){let{prefix:n}=e;if(n!==Z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function hg(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Un=112,dg=18;function vf(r,t,e){let n=Wr(r),o=n+Wr(t),s=new Uint8Array(o+e.byteLength);return Gr(r,s,0),Gr(t,s,n),s.set(e,o),s}var pg=Symbol.for("@ipld/js-cid/CID");var oc={};Dt(oc,{identity:()=>Se});var Ef=0,mg="identity",Af=Ee;function gg(r){return ee(Ef,Af(r))}var Se={code:Ef,name:mg,encode:Af,digest:gg};function ut(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function 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 Zr(r,...t){if(!yg(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", 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 Xr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Bf(r,t){Zr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Zo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ne=(r,t)=>r<<32-t|r>>>t;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)),Zr(r),r}function sc(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Yr=class{clone(){return this._cloneInto()}};function Xo(r){let t=n=>r().update(On(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Yo(r=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(r));if(hr&&typeof hr.randomBytes=="function")return hr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function wg(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var If=(r,t,e)=>r&t^~r&e,kf=(r,t,e)=>r&t^r&e^t&e,Jr=class extends Yr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Zo(this.buffer)}update(t){Xr(this);let{view:e,buffer:n,blockLen:o}=this;t=On(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Zo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Xr(this),Bf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;wg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Zo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Jo=BigInt(4294967295),ic=BigInt(32);function Tf(r,t=!1){return t?{h:Number(r&Jo),l:Number(r>>ic&Jo)}:{h:Number(r>>ic&Jo)|0,l:Number(r&Jo)|0}}function bg(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Tf(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var xg=(r,t)=>BigInt(r>>>0)<<ic|BigInt(t>>>0),vg=(r,t,e)=>r>>>e,Eg=(r,t,e)=>r<<32-e|t>>>e,Ag=(r,t,e)=>r>>>e|t<<32-e,Sg=(r,t,e)=>r<<32-e|t>>>e,_g=(r,t,e)=>r<<64-e|t>>>e-32,Bg=(r,t,e)=>r>>>e-32|t<<64-e,Cg=(r,t)=>t,Ig=(r,t)=>r,kg=(r,t,e)=>r<<e|t>>>32-e,Tg=(r,t,e)=>t<<e|r>>>32-e,Lg=(r,t,e)=>t<<e-32|r>>>64-e,Ng=(r,t,e)=>r<<e-32|t>>>64-e;function Pg(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Rg=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Dg=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Mg=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ug=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Og=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Fg=(r,t,e,n,o,s)=>t+e+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:Rg,add3H:Dg,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))),ze=new Uint32Array(80),Ge=new Uint32Array(80),ac=class extends Jr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(t,e){for(let y=0;y<16;y++,e+=4)ze[y]=t.getUint32(e),Ge[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let x=ze[y-15]|0,A=Ge[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=ze[y-2]|0,k=Ge[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,Ge[y-7],Ge[y-16]),R=F.add4H(V,_,Y,ze[y-7],ze[y-16]);ze[y]=R|0,Ge[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],Ge[y]),k=F.add5H(B,w,x,_,Hg[y],ze[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),R=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,R),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(){ze.fill(0),Ge.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 ac);var es={};Dt(es,{aInRange:()=>qt,abool:()=>oe,abytes:()=>Qr,bitGet:()=>jg,bitLen:()=>fc,bitMask:()=>Vn,bitSet:()=>Zg,bytesToHex:()=>Be,bytesToNumberBE:()=>Ce,bytesToNumberLE:()=>je,concatBytes:()=>Ie,createHmacDrbg:()=>hc,ensureBytes:()=>at,equalBytes:()=>Gg,hexToBytes:()=>pr,hexToNumber:()=>uc,inRange:()=>Fn,isBytes:()=>We,memoized:()=>gr,notImplemented:()=>Yg,numberToBytesBE:()=>Ze,numberToBytesLE:()=>mr,numberToHexUnpadded:()=>dr,numberToVarBytesBE:()=>zg,utf8ToBytes:()=>Wg,validateObject:()=>he});var Qo=BigInt(0),ts=BigInt(1),qg=BigInt(2);function We(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Qr(r){if(!We(r))throw new Error("Uint8Array expected")}function oe(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var $g=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Be(r){Qr(r);let t="";for(let e=0;e<r.length;e++)t+=$g[r[e]];return t}function dr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function uc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}var _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nf(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function pr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=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 Ce(r){return uc(Be(r))}function je(r){return Qr(r),uc(Be(Uint8Array.from(r).reverse()))}function Ze(r,t){return pr(r.toString(16).padStart(t*2,"0"))}function mr(r,t){return Ze(r,t).reverse()}function zg(r){return pr(dr(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=pr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(We(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function Ie(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Qr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Gg(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Wg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var cc=r=>typeof r=="bigint"&&Qo<=r;function Fn(r,t,e){return cc(r)&&cc(t)&&cc(e)&&t<=r&&r<e}function qt(r,t,e,n){if(!Fn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function fc(r){let t;for(t=0;r>Qo;r>>=ts,t+=1);return t}function jg(r,t){return r>>BigInt(t)&ts}function Zg(r,t,e){return r|(e?ts:Qo)<<BigInt(t)}var Vn=r=>(qg<<BigInt(r-1))-ts,lc=r=>new Uint8Array(r),Pf=r=>Uint8Array.from(r);function hc(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=lc(r),o=lc(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>e(o,n,...l),c=(l=lc())=>{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<t;){n=a();let h=n.slice();d.push(h),l+=n.length}return Ie(...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"||We(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function he(r,t,e={}){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(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Yg=()=>{throw new Error("not implemented")};function gr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var gt=BigInt(0),st=BigInt(1),yr=BigInt(2),Jg=BigInt(3),dc=BigInt(4),Rf=BigInt(5),Df=BigInt(8),Qg=BigInt(9),t0=BigInt(16);function Q(r,t){let e=r%t;return e>=gt?e:t+e}function e0(r,t,e){if(t<gt)throw new Error("invalid exponent, negatives unsupported");if(e<=gt)throw new Error("invalid modulus");if(e===st)return gt;let n=st;for(;t>gt;)t&st&&(n=n*r%e),r=r*r%e,t>>=st;return n}function it(r,t,e){let n=r;for(;t-- >gt;)n*=n,n%=e;return n}function rs(r,t){if(r===gt)throw new Error("invert: expected non-zero number");if(t<=gt)throw new Error("invert: expected positive modulus, got "+t);let e=Q(r,t),n=t,o=gt,s=st,i=st,a=gt;for(;e!==gt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==st)throw new Error("invert: does not exist");return Q(o,t)}function r0(r){let t=(r-st)/yr,e,n,o;for(e=r-st,n=0;e%yr===gt;e/=yr,n++);for(o=yr;o<r&&e0(o,t,r)!==r-st;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+st)/dc;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(e+st)/yr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),e),l=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,st<<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%dc===Jg){let t=(r+st)/dc;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Df===Rf){let t=(r-Rf)/Df;return function(n,o){let s=n.mul(o,yr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,yr),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%t0,r0(r)}var Mf=(r,t)=>(Q(r,t)&st)===st,o0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function pc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=o0.reduce((n,o)=>(n[o]="function",n),t);return he(r,e)}function s0(r,t,e){if(e<gt)throw new Error("invalid exponent, negatives unsupported");if(e===gt)return r.ONE;if(e===st)return t;let n=r.ONE,o=t;for(;e>gt;)e&st&&(n=r.mul(n,o)),o=r.sqr(o),e>>=st;return n}function i0(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function mc(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Xe(r,t,e=!1,n={}){if(r<=gt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=mc(r,t);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:gt,ONE:st,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return gt<=c&&c<r},is0:c=>c===gt,isOdd:c=>(c&st)===st,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=>e?mr(c,s):Ze(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?je(c):Ce(c)}});return Object.freeze(a)}function Uf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function gc(r){let t=Uf(r);return t+Math.ceil(t/2)}function Of(r,t,e=!1){let n=r.length,o=Uf(t),s=gc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Ce(r):je(r),a=Q(i,t-st)+st;return e?mr(a,o):Ze(a,o)}var Ff=BigInt(0),ns=BigInt(1);function yc(r,t){let e=t.negate();return r?e:t}function Vf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function wc(r,t){Vf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function c0(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function l0(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var bc=new WeakMap,Hf=new WeakMap;function xc(r){return Hf.get(r)||1}function os(r,t){return{constTimeNegate:yc,hasPrecomputes(e){return xc(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Ff;)n&ns&&(o=o.add(s)),s=s.double(),n>>=ns;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=wc(n,t),i=[],a=e,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(e,n,o){let{windows:s,windowSize:i}=wc(e,t),a=r.ZERO,c=r.BASE,u=BigInt(2**e-1),f=2**e,l=BigInt(e);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(yc(w,n[m])):a=a.add(yc(b,n[g]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=wc(e,t),c=BigInt(2**e-1),u=2**e,f=BigInt(e);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(e,n,o){let s=bc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&bc.set(n,o(s))),s},wNAFCached(e,n,o){let s=xc(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=xc(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Vf(n,t),Hf.set(e,n),bc.delete(e)}}}function ss(r,t,e,n){if(c0(e,r),l0(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=fc(BigInt(e.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((t.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(e[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 pc(r.Fp),he(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...mc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var se=BigInt(0),$t=BigInt(1),is=BigInt(2),u0=BigInt(8),f0={zip215:!0};function h0(r){let t=Hn(r);return he(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Kf(r){let t=h0(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=is<<BigInt(a*8)-$t,f=e.create,l=Xe(t.n,t.nBitLength),d=t.uvRatio||((S,E)=>{try{return{isValid:!0,value:e.sqrt(S*e.inv(E))}}catch{return{isValid:!1,value:se}}}),h=t.adjustScalarBytes||(S=>S),p=t.domain||((S,E,C)=>{if(oe("phflag",C),E.length||C)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){qt("coordinate "+S,E,se,u)}function g(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=gr((S,E)=>{let{ex:C,ey:L,ez:M}=S,U=S.is0();E==null&&(E=U?u0:e.inv(M));let K=f(C*E),$=f(L*E),O=f(M*E);if(U)return{x:se,y:$t};if(O!==$t)throw new Error("invZ was invalid");return{x:K,y:$}}),b=gr(S=>{let{a:E,d:C}=t;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),nt=f(J*J),bt=f($*E),xt=f(J*f(bt+O)),Et=f(nt+f(C*f($*O)));if(xt!==Et)throw new Error("bad point: equation left != right (1)");let Bt=f(L*M),Kt=f(U*K);if(Bt!==Kt)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,$t,f(C*L))}static normalizeZ(E){let C=e.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),nt=f(L*$),bt=f(K*M);return O===J&&nt===bt}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=t,{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,nt=f(f(J*J)-U-K),bt=O+K,xt=bt-$,Et=O-K,Bt=f(nt*xt),Kt=f(bt*Et),Rt=f(nt*Et),fe=f(xt*bt);return new y(Bt,Kt,fe,Rt)}add(E){g(E);let{a:C,d:L}=t,{ex:M,ey:U,ez:K,et:$}=this,{ex:O,ey:J,ez:nt,et:bt}=E;if(C===BigInt(-1)){let Yu=f((U-M)*(J+O)),Ju=f((U+M)*(J-O)),qa=f(Ju-Yu);if(qa===se)return this.double();let Qu=f(K*is*bt),tf=f($*is*nt),ef=tf+Qu,rf=Ju+Yu,nf=tf-Qu,vm=f(ef*qa),Em=f(rf*nf),Am=f(ef*nf),Sm=f(qa*rf);return new y(vm,Em,Sm,Am)}let xt=f(M*O),Et=f(U*J),Bt=f($*L*bt),Kt=f(K*nt),Rt=f((M+U)*(O+J)-xt-Et),fe=Kt-Bt,be=Kt+Bt,Tn=f(Et-C*xt),ym=f(Rt*fe),wm=f(be*Tn),bm=f(Rt*Tn),xm=f(fe*be);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;qt("scalar",C,$t,n);let{p:L,f:M}=this.wNAF(C);return y.normalizeZ([L,M])[0]}multiplyUnsafe(E,C=y.ZERO){let L=E;return qt("scalar",L,se,n),L===se?A:this.is0()||L===$t?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}=t;return E===$t?this:this.multiplyUnsafe(E)}static fromHex(E,C=!1){let{d:L,a:M}=t,U=e.BYTES;E=at("pointHex",E,U),oe("zip215",C);let K=E.slice(),$=E[U-1];K[U-1]=$&-129;let O=je(K),J=C?u:e.ORDER;qt("pointHex.y",O,se,J);let nt=f(O*O),bt=f(nt-$t),xt=f(L*nt-M),{isValid:Et,value:Bt}=d(bt,xt);if(!Et)throw new Error("Point.fromHex: invalid y coordinate");let Kt=(Bt&$t)===$t,Rt=($&128)!==0;if(!C&&Bt===se&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Kt&&(Bt=f(-Bt)),y.fromAffine({x:Bt,y:O})}static fromPrivateKey(E){return k(E).point}toRawBytes(){let{x:E,y:C}=this.toAffine(),L=mr(C,e.BYTES);return L[L.length-1]|=E&$t?128:0,L}toHex(){return Be(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,$t,f(t.Gx*t.Gy)),y.ZERO=new y(se,$t,$t,se);let{BASE:x,ZERO:A}=y,_=os(y,a*8);function v(S){return Q(S,n)}function B(S){return v(je(S))}function k(S){let E=e.BYTES;S=at("private key",S,E);let C=at("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=Ie(...E);return B(s(p(C,at("context",S),!!o)))}function V(S,E,C={}){S=at("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);qt("signature.s",J,se,n);let nt=Ie($,mr(J,e.BYTES));return at("result",nt,e.BYTES*2)}let R=f0;function I(S,E,C,L=R){let{context:M,zip215:U}=L,K=e.BYTES;S=at("signature",S,2*K),E=at("message",E),C=at("publicKey",C,K),U!==void 0&&oe("zip215",U),o&&(E=o(E));let $=je(S.slice(K,2*K)),O,J,nt;try{O=y.fromHex(C,U),J=y.fromHex(S.slice(0,K),U),nt=x.multiplyUnsafe($)}catch{return!1}if(!U&&O.isSmallOrder())return!1;let bt=H(M,J.toRawBytes(),O.toRawBytes(),E);return J.add(O.multiplyUnsafe(bt)).subtract(nt).clearCofactor().equals(y.ZERO)}return x._setWindowSize(8),{CURVE:t,getPublicKey:Y,sign:V,verify:I,ExtendedPoint:y,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(e.BYTES),precompute(S=8,E=y.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var vc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),qf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),q1=BigInt(0),d0=BigInt(1),$f=BigInt(2),$1=BigInt(3),p0=BigInt(5),m0=BigInt(8);function g0(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=vc,a=r*r%s*r%s,c=it(a,$f,s)*a%s,u=it(c,d0,s)*r%s,f=it(u,p0,s)*u%s,l=it(f,t,s)*f%s,d=it(l,e,s)*l%s,h=it(d,n,s)*d%s,p=it(h,o,s)*h%s,m=it(p,o,s)*h%s,g=it(m,t,s)*f%s;return{pow_p_5_8:it(g,$f,s)*r%s,b2:a}}function y0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function w0(r,t){let e=vc,n=Q(t*t*t,e),o=Q(n*n*t,e),s=g0(r*o).pow_p_5_8,i=Q(r*n*s,e),a=Q(t*i*i,e),c=i,u=Q(i*qf,e),f=a===r,l=a===Q(-r,e),d=a===Q(-r*qf,e);return f&&(i=c),(l||d)&&(i=u),Mf(i,e)&&(i=Q(-i,e)),{isValid:f||l,value:i}}var b0=Xe(vc,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,Ec=32;function zf(){let r=Kn.utils.randomPrivateKey(),t=Kn.getPublicKey(r);return{privateKey:v0(r,t),publicKey:t}}function Gf(r,t){let e=r.subarray(0,Ec);return Kn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Wf(r,t,e){return Kn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function v0(r,t){let e=new Uint8Array(cs);for(let n=0;n<Ec;n++)e[n]=r[n],e[Ec+n]=t[n];return e}var qn=class{type="Ed25519";raw;constructor(t){this.raw=us(t,as)}toMultihash(){return Se.digest(de(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return Wf(this.raw,e,t)}},ls=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=us(t,cs),this.publicKey=new qn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return Gf(this.raw,t)}};function Ac(r){return r=us(r,as),new qn(r)}async function Zf(){let{privateKey:r,publicKey:t}=zf();return new ls(r,t)}function us(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function ft(r=0){return new Uint8Array(r)}function Ct(r=0){return new Uint8Array(r)}var E0=Math.pow(2,7),A0=Math.pow(2,14),S0=Math.pow(2,21),Sc=Math.pow(2,28),_c=Math.pow(2,35),Bc=Math.pow(2,42),Cc=Math.pow(2,49),X=128,It=127;function pt(r){if(r<E0)return 1;if(r<A0)return 2;if(r<S0)return 3;if(r<Sc)return 4;if(r<_c)return 5;if(r<Bc)return 6;if(r<Cc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ic(r,t,e=0){switch(pt(r)){case 8:t[e++]=r&255|X,r/=128;case 7:t[e++]=r&255|X,r/=128;case 6:t[e++]=r&255|X,r/=128;case 5:t[e++]=r&255|X,r/=128;case 4:t[e++]=r&255|X,r>>>=7;case 3:t[e++]=r&255|X,r>>>=7;case 2:t[e++]=r&255|X,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function _0(r,t,e=0){switch(pt(r)){case 8:t.set(e++,r&255|X),r/=128;case 7:t.set(e++,r&255|X),r/=128;case 6:t.set(e++,r&255|X),r/=128;case 5:t.set(e++,r&255|X),r/=128;case 4:t.set(e++,r&255|X),r>>>=7;case 3:t.set(e++,r&255|X),r>>>=7;case 2:t.set(e++,r&255|X),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function kc(r,t){let e=r[t],n=0;if(n+=e&It,e<X||(e=r[t+1],n+=(e&It)<<7,e<X)||(e=r[t+2],n+=(e&It)<<14,e<X)||(e=r[t+3],n+=(e&It)<<21,e<X)||(e=r[t+4],n+=(e&It)*Sc,e<X)||(e=r[t+5],n+=(e&It)*_c,e<X)||(e=r[t+6],n+=(e&It)*Bc,e<X)||(e=r[t+7],n+=(e&It)*Cc,e<X))return n;throw new RangeError("Could not decode varint")}function B0(r,t){let e=r.get(t),n=0;if(n+=e&It,e<X||(e=r.get(t+1),n+=(e&It)<<7,e<X)||(e=r.get(t+2),n+=(e&It)<<14,e<X)||(e=r.get(t+3),n+=(e&It)<<21,e<X)||(e=r.get(t+4),n+=(e&It)*Sc,e<X)||(e=r.get(t+5),n+=(e&It)*_c,e<X)||(e=r.get(t+6),n+=(e&It)*Bc,e<X)||(e=r.get(t+7),n+=(e&It)*Cc,e<X))return n;throw new RangeError("Could not decode varint")}function kt(r,t,e=0){return t==null&&(t=Ct(pt(r))),t instanceof Uint8Array?Ic(r,t,e):_0(r,t,e)}function ie(r,t=0){return r instanceof Uint8Array?kc(r,t):B0(r,t)}var Tc=new Float32Array([-0]),Ye=new Uint8Array(Tc.buffer);function Xf(r,t,e){Tc[0]=r,t[e]=Ye[0],t[e+1]=Ye[1],t[e+2]=Ye[2],t[e+3]=Ye[3]}function Yf(r,t){return Ye[0]=r[t],Ye[1]=r[t+1],Ye[2]=r[t+2],Ye[3]=r[t+3],Tc[0]}var Lc=new Float64Array([-0]),Tt=new Uint8Array(Lc.buffer);function Jf(r,t,e){Lc[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Qf(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],Lc[0]}var C0=BigInt(Number.MAX_SAFE_INTEGER),I0=BigInt(Number.MIN_SAFE_INTEGER),jt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return br;if(t<C0&&t>I0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>th&&(o=0n,++n>th&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return br;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):br}},br=new jt(0,0);br.toBigInt=function(){return 0n};br.zzEncode=br.zzDecode=function(){return this};br.length=function(){return 1};var th=4294967296n;function eh(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function rh(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Nc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ae(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function fs(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Pc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ae(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ae(this,4);return fs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ae(this,4);return fs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ae(this,4);let t=Yf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ae(this,4);let t=Qf(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ae(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return rh(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ae(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ae(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new jt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ae(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ae(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ae(this,8);let t=fs(this.buf,this.pos+=4),e=fs(this.buf,this.pos+=4);return new jt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=kc(this.buf,this.pos);return this.pos+=pt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Rc(r){return new Pc(r instanceof Uint8Array?r:r.subarray())}function Mt(r,t,e){let n=Rc(r);return t.decode(n,void 0,e)}var Dc={};Dt(Dc,{base10:()=>k0});var k0=$e({prefix:"9",name:"base10",alphabet:"0123456789"});var Mc={};Dt(Mc,{base16:()=>T0,base16upper:()=>L0});var T0=lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L0=lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uc={};Dt(Uc,{base2:()=>N0});var N0=lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Oc={};Dt(Oc,{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,t,e)=>(r[e]=t,r),[]),R0=oh.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function D0(r){return r.reduce((t,e)=>(t+=P0[e],t),"")}function M0(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=R0[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var U0=zr({prefix:"\u{1F680}",name:"base256emoji",encode:D0,decode:M0});var Hc={};Dt(Hc,{base64:()=>Fc,base64pad:()=>O0,base64url:()=>Vc,base64urlpad:()=>F0});var Fc=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O0=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vc=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),F0=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Kc={};Dt(Kc,{base8:()=>V0});var V0=lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qc={};Dt(qc,{identity:()=>H0});var H0=zr({prefix:"\0",name:"identity",encode:r=>ff(r),decode:r=>uf(r)});var Av=new TextEncoder,Sv=new TextDecoder;var Gc={};Dt(Gc,{sha256:()=>tn,sha512:()=>$0});function zc({name:r,code:t,encode:e}){return new $c(r,t,e)}var $c=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?ee(this.code,e):e.then(n=>ee(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ih(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var tn=zc({name:"sha2-256",code:18,encode:ih("SHA-256")}),$0=zc({name:"sha2-512",code:19,encode:ih("SHA-512")});var $n={...qc,...Uc,...Kc,...Dc,...Mc,...tc,...ec,...Qa,...Hc,...Oc},Mv={...Gc,...oc};function ch(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ah=ch("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Wc=ch("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Ct(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),z0={utf8:ah,"utf-8":ah,hex:$n.base16,latin1:Wc,ascii:Wc,binary:Wc,...$n},hs=z0;function P(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function jc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Ct(i);o+i>t&&(n=Ct(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var xr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Zc(){}var Yc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},G0=jc();function W0(r){return globalThis.Buffer!=null?Ct(r):G0(r)}var Gn=class{len;head;tail;states;constructor(){this.len=0,this.head=new xr(Zc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Jc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ds,10,jt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=jt.fromBigInt(t);return this._push(ds,e.length(),e)}uint64Number(t){return this._push(Ic,pt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=jt.fromBigInt(t).zzEncode();return this._push(ds,e.length(),e)}sint64Number(t){let e=jt.fromNumber(t).zzEncode();return this._push(ds,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Xc,1,t?1:0)}fixed32(t){return this._push(zn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=jt.fromBigInt(t);return this._push(zn,4,e.lo)._push(zn,4,e.hi)}fixed64Number(t){let e=jt.fromNumber(t);return this._push(zn,4,e.lo)._push(zn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Xf,4,t)}double(t){return this._push(Jf,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Xc,1,0):this.uint32(e)._push(Z0,e,t)}string(t){let e=eh(t);return e!==0?this.uint32(e)._push(Nc,e,t):this._push(Xc,1,0)}fork(){return this.states=new Yc(this),this.head=this.tail=new xr(Zc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new xr(Zc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=W0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Xc(r,t,e){t[e]=r&255}function j0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Jc=class extends xr{next;constructor(t,e){super(j0,t,e),this.next=void 0}};function ds(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function zn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Z0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Gn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(X0,t,r),this},Gn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Y0,t,r),this});function X0(r,t,e){t.set(r,e)}function Y0(r,t,e){r.length<40?Nc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function Qc(){return new Gn}function Ut(r,t){let e=Qc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var en;(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"})(en||(en={}));function ps(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function tl(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return ps("enum",en.VARINT,e,n)}function Ot(r,t){return ps("message",en.LENGTH_DELIMITED,r,t)}var vr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Wn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var yt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(yt||(yt={}));var el;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(el||(el={}));(function(r){r.codec=()=>tl(el)})(yt||(yt={}));var pe;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),yt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=yt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(pe||(pe={}));var rl;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),yt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=yt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(rl||(rl={}));var oo={};Dt(oo,{MAX_RSA_KEY_SIZE:()=>li,generateRSAKeyPair:()=>gl,jwkToJWKKeyPair:()=>ud,jwkToPkcs1:()=>gy,jwkToPkix:()=>pl,jwkToRSAPrivateKey:()=>ld,pkcs1ToJwk:()=>id,pkcs1ToRSAPrivateKey:()=>cd,pkixToJwk:()=>ad,pkixToRSAPublicKey:()=>ml});function J0(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function nl(r,...t){if(!J0(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function ol(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function uh(r,t){nl(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var gs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ce=(r,t)=>r<<32-t|r>>>t;function Q0(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function sl(r){return typeof r=="string"&&(r=Q0(r)),nl(r),r}var ms=class{clone(){return this._cloneInto()}};function fh(r){let t=n=>r().update(sl(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function hh(r=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(r));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function ty(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var dh=(r,t,e)=>r&t^~r&e,ph=(r,t,e)=>r&t^r&e^t&e,ys=class extends ms{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=gs(this.buffer)}update(t){ol(this);let{view:e,buffer:n,blockLen:o}=this;t=sl(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ol(this),uh(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;ty(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var ey=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]),Je=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qe=new Uint32Array(64),il=class extends ys{constructor(){super(64,32,8,!1),this.A=Je[0]|0,this.B=Je[1]|0,this.C=Je[2]|0,this.D=Je[3]|0,this.E=Je[4]|0,this.F=Je[5]|0,this.G=Je[6]|0,this.H=Je[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)Qe[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Qe[l-15],h=Qe[l-2],p=ce(d,7)^ce(d,18)^d>>>3,m=ce(h,17)^ce(h,19)^h>>>10;Qe[l]=m+Qe[l-7]+p+Qe[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=ce(a,6)^ce(a,11)^ce(a,25),h=f+d+dh(a,c,u)+ey[l]+Qe[l]|0,m=(ce(n,2)^ce(n,13)^ce(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(){Qe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ws=fh(()=>new il);var q=fr(mh());function Ar(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function tr(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*t);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function vs(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function cl(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Ar(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Ar(s,8)-n}function gh(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function yh(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function zt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var _2=Math.log(2);function Es(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ll(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Pe(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Zn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return ll(this.items)}},jn=[new Uint8Array([1])],wh="0123456789";var an="",le=new ArrayBuffer(0),ul=new Uint8Array(0),Xn="EndOfContent",xh="OCTET STRING",vh="BIT STRING";function Re(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):ul}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Pe(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",le)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Te=class{constructor({blockLength:t=0,error:e=an,warnings:n=[],valueBeforeDecode:o=ul}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Te.NAME="baseBlock";var Lt=class extends Te{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var As=class extends Re(Te){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?q.BufferSourceConverter.toUint8Array(t.valueHex):ul,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",le}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=tr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Ar(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};As.NAME="identificationBlock";var Ss=class extends Te{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ar(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=tr(this.length,8);if(o.byteLength>127)return this.error="Too big length",le;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Ss.NAME="lengthBlock";var T={},At=class extends Te{constructor({name:t=an,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new As(o),this.lenBlock=new Ss(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new Zn;e||Eh(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?le:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return yh(e,n)}};At.NAME="BaseBlock";function Eh(r){if(r instanceof T.Constructed)for(let t of r.valueBlock.value)Eh(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var _s=class extends At{constructor({value:t=an,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};_s.NAME="BaseStringBlock";var Bs=class extends Re(Lt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Bs.NAME="PrimitiveValueBlock";var Ah,Cs=class extends At{constructor(t={}){super(t,Bs),this.idBlock.isConstructed=!1}};Ah=Cs;T.Primitive=Ah;Cs.NAME="PRIMITIVE";function uy(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function ai(r,t=0,e=r.length){let n=t,o=new At({},Lt),s=new Te;if(!Pe(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=At;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=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,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function fl(r){if(!r.byteLength){let t=new At({},Lt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ai(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function fy(r,t){return r?1:t}var me=class extends Lt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;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(t,e){let n=e||new Zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?le:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};me.NAME="ConstructedValueBlock";var Sh,er=class extends At{constructor(t={}){super(t,me),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var _m=Object.create;var Mo=Object.defineProperty;var Bm=Object.getOwnPropertyDescriptor;var Cm=Object.getOwnPropertyNames;var Im=Object.getPrototypeOf,km=Object.prototype.hasOwnProperty;var Qt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Rt=(r,t)=>{for(var e in t)Mo(r,e,{get:t[e],enumerable:!0})},of=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cm(t))!km.call(r,o)&&o!==e&&Mo(r,o,{get:()=>t[o],enumerable:!(n=Bm(t,o))||n.enumerable});return r};var hr=(r,t,e)=>(e=r!=null?_m(Im(r)):{},of(t||!r||!r.__esModule?Mo(e,"default",{value:r,enumerable:!0}):e,r)),Tm=r=>of(Mo({},"__esModule",{value:!0}),r);var mh=Qt(nn=>{"use strict";var ry="[object ArrayBuffer]",ke=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===ry}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},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(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=ke.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Xt=class{static toString(t,e=!1){let n=ke.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},xs=class r{static isHex(t){return typeof t===ll&&ny.test(t)}static isBase64(t){return typeof t===ll&&oy.test(t)}static isBase64Url(t){return typeof t===ll&&sy.test(t)}static ToString(t,e="utf8"){let n=ke.toUint8Array(t);switch(e.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Xt.toString(n,!0);case"utf16":case"utf16be":return Xt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Xt.fromString(t,!0);case"utf16":case"utf16be":return Xt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=ke.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return bs.fromString(t);case"utf16":case"utf16be":return Xt.fromString(t);case"utf16le":case"usc2":return Xt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return bs.toString(t);case"utf16":case"utf16be":return Xt.toString(t);case"utf16le":case"usc2":return Xt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=ke.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=ke.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Xt.toString(t,e)}static FromUtf16String(t,e=!1){return Xt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};xs.DEFAULT_UTF8_ENCODING="utf8";function iy(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function ay(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function cy(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}nn.BufferSourceConverter=ke;nn.Convert=xs;nn.assign=iy;nn.combine=ay;nn.isEqual=cy});var Nd=Qt((bA,Bl)=>{"use strict";var Ny=Object.prototype.hasOwnProperty,Ht="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(Ht=!1));function Py(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Ld(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Py(e,n||r,o),i=Ht?Ht+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function di(r,t){--r._eventsCount===0?r._events=new ho:delete r._events[t]}function Nt(){this._events=new ho,this._eventsCount=0}Nt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Ny.call(e,n)&&t.push(Ht?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Nt.prototype.listeners=function(t){var e=Ht?Ht+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Nt.prototype.listenerCount=function(t){var e=Ht?Ht+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(t,e,n,o,s,i){var a=Ht?Ht+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,n);break;case 4:c[l].fn.call(c[l].context,e,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Nt.prototype.on=function(t,e,n){return Ld(this,t,e,n,!1)};Nt.prototype.once=function(t,e,n){return Ld(this,t,e,n,!0)};Nt.prototype.removeListener=function(t,e,n,o){var s=Ht?Ht+t:t;if(!this._events[s])return this;if(!e)return di(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!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!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:di(this,s)}return this};Nt.prototype.removeAllListeners=function(t){var e;return t?(e=Ht?Ht+t:t,this._events[e]&&di(this,e)):(this._events=new ho,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=Ht;Nt.EventEmitter=Nt;typeof Bl<"u"&&(Bl.exports=Nt)});var Ud=Qt((KA,Md)=>{Md.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Qd=Qt((S8,Jd)=>{"use strict";Jd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var sp=Qt((np,op)=>{"use strict";var vi=Qd(),{hasOwnProperty:ep}=Object.prototype,{propertyIsEnumerable:ow}=Object,yn=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),sw=np,tp={concatArrays:!1,ignoreUndefined:!1},Ei=r=>{let t=[];for(let e in r)ep.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)ow.call(r,n)&&t.push(n)}return t};function wn(r){return Array.isArray(r)?iw(r):vi(r)?aw(r):r}function iw(r){let t=r.slice(0,0);return Ei(r).forEach(e=>{yn(t,e,wn(r[e]))}),t}function aw(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ei(r).forEach(e=>{yn(t,e,wn(r[e]))}),t}var rp=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?yn(r,o,Zl(r[o],t[o],n)):yn(r,o,wn(t[o])))}),r),cw=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)ep.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)),e)}),n};function Zl(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?cw(r,t,e):!vi(t)||!vi(r)?wn(t):rp(r,t,Ei(t),e)}op.exports=function(...r){let t=Zl(wn(tp),this!==sw&&this||{},tp),e={_:{}};for(let n of r)if(n!==void 0){if(!vi(n))throw new TypeError("`"+n+"` is not an Option Object");e=Zl(e,{_:n},t)}return e._}});var up=Qt((yo,ki)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%4,g=h.length-m,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},e.x86.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,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)},e.x64.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,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=e),yo.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(yo)});var hp=Qt((J8,fp)=>{fp.exports=up()});var Up=Qt(_o=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+e(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),_o.ip2long=i,_o.long2ip=a,_o.Netmask=r}).call(_o)});var em=Qt((d4,tm)=>{function Jt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}tm.exports=Jt;Jt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Jt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Jt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Jt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Jt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Jt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Jt.prototype.start=Jt.prototype.try;Jt.prototype.errors=function(){return this._errors};Jt.prototype.attempts=function(){return this._attempts};Jt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var rm=Qt(Or=>{var Fb=em();Or.operation=function(r){var t=Or.timeouts(r);return new Fb(t,{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 t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Or.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Or.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Or.operation(t),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=t}}});var om=Qt((m4,nm)=>{nm.exports=rm()});var px={};Rt(px,{createLibp2p:()=>dx});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 Ex=Symbol.for("@libp2p/transport");var He;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(He||(He={}));var te=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Hr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},Ln=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Fo=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Kr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Vo=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},qr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Ke=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Ho=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ko=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Nn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},qo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var $o=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},xe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var $r=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var zr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},zo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Go=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},qe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var ot=(r,...t)=>{try{[...t]}catch{}};var ve=class extends EventTarget{#t=new Map;constructor(){super(),ot(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Wo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function af(...r){let t=[];for(let e of r)Wo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function cf(...r){let t=[];for(let e of r)Wo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Pn=Symbol.for("@libp2p/service-capabilities"),Xa=Symbol.for("@libp2p/service-dependencies");var ec={};Rt(ec,{base58btc:()=>Z,base58flickr:()=>Mm});var Jx=new Uint8Array(0);function lf(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function uf(r){return new TextEncoder().encode(r)}function ff(r){return new TextDecoder().decode(r)}function Lm(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,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=e[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-${t} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Nm=Lm,Pm=Nm,df=Pm;var Ya=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ja=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return pf(this,t)}},Qa=class{decoders;constructor(t){this.decoders=t}or(t){return pf(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function pf(r,t){return new Qa({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var tc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ya(t,e,n),this.decoder=new Ja(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Gr({name:r,prefix:t,encode:e,decode:n}){return new tc(r,t,e,n)}function $e({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=df(e,r);return Gr({prefix:t,name:r,encode:n,decode:s=>Ee(o(s))})}function Dm(r,t,e,n){let o={};for(let f=0;f<t.length;++f)o[t[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|l,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Rm(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Gr({prefix:t,name:r,encode(o){return Rm(o,n,e)},decode(o){return Dm(o,n,e,r)}})}var Z=$e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mm=$e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var rc={};Rt(rc,{base32:()=>Wt,base32hex:()=>Vm,base32hexpad:()=>Km,base32hexpadupper:()=>qm,base32hexupper:()=>Hm,base32pad:()=>Om,base32padupper:()=>Fm,base32upper:()=>Um,base32z:()=>$m});var Wt=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Um=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Om=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fm=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vm=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hm=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Km=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qm=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$m=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nc={};Rt(nc,{base36:()=>Dn,base36upper:()=>zm});var Dn=$e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zm=$e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gm=yf,mf=128,Wm=127,jm=~Wm,Zm=Math.pow(2,31);function yf(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Zm;)t[e++]=r&255|mf,r/=128;for(;r&jm;)t[e++]=r&255|mf,r>>>=7;return t[e]=r|0,yf.bytes=e-n+1,t}var Xm=oc,Ym=128,gf=127;function oc(r,n){var e=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++],e+=o<28?(i&gf)<<o:(i&gf)*Math.pow(2,o),o+=7}while(i>=Ym);return oc.bytes=s-n,e}var Jm=Math.pow(2,7),Qm=Math.pow(2,14),tg=Math.pow(2,21),eg=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<tg?3:r<eg?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,t=0){return[Rn.decode(r,t),Rn.decode.bytes]}function Wr(r,t,e=0){return Rn.encode(r,t,e),t}function jr(r){return Rn.encodingLength(r)}function ee(r,t){let e=t.byteLength,n=jr(r),o=n+jr(e),s=new Uint8Array(o+e);return Wr(r,s,0),Wr(e,s,n),s.set(t,o),new Zr(r,e,t,s)}function re(r){let t=Ee(r),[e,n]=Mn(t),[o,s]=Mn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Zr(e,o,i,t)}function wf(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&lf(r.bytes,e.bytes)}}var Zr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function bf(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return fg(e,sc(r),t??Z.encoder);default:return hg(e,sc(r),t??Wt.encoder)}}var xf=new WeakMap;function sc(r){let t=xf.get(r);if(t==null){let e=new Map;return xf.set(r,e),e}return t}var mt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==dg)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=ee(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&wf(t.multihash,n.multihash)}toString(t){return bf(this,t)}toJSON(){return{"/":bf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??vf(n,o,s.bytes))}else if(e[pg]===!0){let{version:n,multihash:o,code:s}=e,i=re(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Un)throw new Error(`Version 0 CID must use dag-pb (code: ${Un}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=vf(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Un,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Zr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=Mn(t.subarray(e));return e+=d,l},o=n(),s=Un;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=ug(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sc(s).set(n,t),s}};function ug(r,t){switch(r[0]){case"Q":{let e=t??Z;return[Z.prefix,e.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}case Wt.prefix:{let e=t??Wt;return[Wt.prefix,e.decode(r)]}case Dn.prefix:{let e=t??Dn;return[Dn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function fg(r,t,e){let{prefix:n}=e;if(n!==Z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function hg(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Un=112,dg=18;function vf(r,t,e){let n=jr(r),o=n+jr(t),s=new Uint8Array(o+e.byteLength);return Wr(r,s,0),Wr(t,s,n),s.set(e,o),s}var pg=Symbol.for("@ipld/js-cid/CID");var ic={};Rt(ic,{identity:()=>Se});var Ef=0,mg="identity",Af=Ee;function gg(r){return ee(Ef,Af(r))}var Se={code:Ef,name:mg,encode:Af,digest:gg};function ut(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function 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,...t){if(!yg(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", 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,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Bf(r,t){Xr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var dr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Zo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ne=(r,t)=>r<<32-t|r>>>t;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 t=0;for(let n=0;n<r.length;n++){let o=r[n];Xr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Jr=class{clone(){return this._cloneInto()}};function Xo(r){let t=n=>r().update(On(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}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,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var If=(r,t,e)=>r&t^~r&e,kf=(r,t,e)=>r&t^r&e^t&e,Qr=class extends Jr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Zo(this.buffer)}update(t){Yr(this);let{view:e,buffer:n,blockLen:o}=this;t=On(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Zo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Yr(this),Bf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;wg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Zo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Jo=BigInt(4294967295),cc=BigInt(32);function Tf(r,t=!1){return t?{h:Number(r&Jo),l:Number(r>>cc&Jo)}:{h:Number(r>>cc&Jo)|0,l:Number(r&Jo)|0}}function bg(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Tf(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var xg=(r,t)=>BigInt(r>>>0)<<cc|BigInt(t>>>0),vg=(r,t,e)=>r>>>e,Eg=(r,t,e)=>r<<32-e|t>>>e,Ag=(r,t,e)=>r>>>e|t<<32-e,Sg=(r,t,e)=>r<<32-e|t>>>e,_g=(r,t,e)=>r<<64-e|t>>>e-32,Bg=(r,t,e)=>r>>>e-32|t<<64-e,Cg=(r,t)=>t,Ig=(r,t)=>r,kg=(r,t,e)=>r<<e|t>>>32-e,Tg=(r,t,e)=>t<<e|r>>>32-e,Lg=(r,t,e)=>t<<e-32|r>>>64-e,Ng=(r,t,e)=>r<<e-32|t>>>64-e;function Pg(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Dg=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Rg=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Mg=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ug=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Og=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Fg=(r,t,e,n,o,s)=>t+e+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))),ze=new Uint32Array(80),Ge=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:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(t,e){for(let y=0;y<16;y++,e+=4)ze[y]=t.getUint32(e),Ge[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let x=ze[y-15]|0,A=Ge[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=ze[y-2]|0,k=Ge[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,Ge[y-7],Ge[y-16]),D=F.add4H(V,_,Y,ze[y-7],ze[y-16]);ze[y]=D|0,Ge[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],Ge[y]),k=F.add5H(B,w,x,_,Hg[y],ze[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(){ze.fill(0),Ge.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 es={};Rt(es,{aInRange:()=>qt,abool:()=>oe,abytes:()=>tn,bitGet:()=>jg,bitLen:()=>dc,bitMask:()=>Vn,bitSet:()=>Zg,bytesToHex:()=>Be,bytesToNumberBE:()=>Ce,bytesToNumberLE:()=>je,concatBytes:()=>Ie,createHmacDrbg:()=>pc,ensureBytes:()=>at,equalBytes:()=>Gg,hexToBytes:()=>mr,hexToNumber:()=>hc,inRange:()=>Fn,isBytes:()=>We,memoized:()=>yr,notImplemented:()=>Yg,numberToBytesBE:()=>Ze,numberToBytesLE:()=>gr,numberToHexUnpadded:()=>pr,numberToVarBytesBE:()=>zg,utf8ToBytes:()=>Wg,validateObject:()=>he});var Qo=BigInt(0),ts=BigInt(1),qg=BigInt(2);function We(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function tn(r){if(!We(r))throw new Error("Uint8Array expected")}function oe(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var $g=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Be(r){tn(r);let t="";for(let e=0;e<r.length;e++)t+=$g[r[e]];return t}function pr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function hc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}var _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nf(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function mr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=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 Ce(r){return hc(Be(r))}function je(r){return tn(r),hc(Be(Uint8Array.from(r).reverse()))}function Ze(r,t){return mr(r.toString(16).padStart(t*2,"0"))}function gr(r,t){return Ze(r,t).reverse()}function zg(r){return mr(pr(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=mr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(We(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function Ie(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];tn(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Gg(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function 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,t,e){return uc(r)&&uc(t)&&uc(e)&&t<=r&&r<e}function qt(r,t,e,n){if(!Fn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function dc(r){let t;for(t=0;r>Qo;r>>=ts,t+=1);return t}function jg(r,t){return r>>BigInt(t)&ts}function Zg(r,t,e){return r|(e?ts:Qo)<<BigInt(t)}var Vn=r=>(qg<<BigInt(r-1))-ts,fc=r=>new Uint8Array(r),Pf=r=>Uint8Array.from(r);function pc(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=fc(r),o=fc(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>e(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<t;){n=a();let h=n.slice();d.push(h),l+=n.length}return Ie(...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"||We(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function he(r,t,e={}){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(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Yg=()=>{throw new Error("not implemented")};function yr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var gt=BigInt(0),st=BigInt(1),wr=BigInt(2),Jg=BigInt(3),mc=BigInt(4),Df=BigInt(5),Rf=BigInt(8),Qg=BigInt(9),t0=BigInt(16);function Q(r,t){let e=r%t;return e>=gt?e:t+e}function e0(r,t,e){if(t<gt)throw new Error("invalid exponent, negatives unsupported");if(e<=gt)throw new Error("invalid modulus");if(e===st)return gt;let n=st;for(;t>gt;)t&st&&(n=n*r%e),r=r*r%e,t>>=st;return n}function it(r,t,e){let n=r;for(;t-- >gt;)n*=n,n%=e;return n}function rs(r,t){if(r===gt)throw new Error("invert: expected non-zero number");if(t<=gt)throw new Error("invert: expected positive modulus, got "+t);let e=Q(r,t),n=t,o=gt,s=st,i=st,a=gt;for(;e!==gt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==st)throw new Error("invert: does not exist");return Q(o,t)}function r0(r){let t=(r-st)/wr,e,n,o;for(e=r-st,n=0;e%wr===gt;e/=wr,n++);for(o=wr;o<r&&e0(o,t,r)!==r-st;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+st)/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=(e+st)/wr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),e),l=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,st<<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 t=(r+st)/mc;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Rf===Df){let t=(r-Df)/Rf;return function(n,o){let s=n.mul(o,wr),i=n.pow(s,t),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%t0,r0(r)}var Mf=(r,t)=>(Q(r,t)&st)===st,o0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=o0.reduce((n,o)=>(n[o]="function",n),t);return he(r,e)}function s0(r,t,e){if(e<gt)throw new Error("invalid exponent, negatives unsupported");if(e===gt)return r.ONE;if(e===st)return t;let n=r.ONE,o=t;for(;e>gt;)e&st&&(n=r.mul(n,o)),o=r.sqr(o),e>>=st;return n}function i0(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function yc(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Xe(r,t,e=!1,n={}){if(r<=gt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=yc(r,t);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:gt,ONE:st,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return gt<=c&&c<r},is0:c=>c===gt,isOdd:c=>(c&st)===st,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=>e?gr(c,s):Ze(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?je(c):Ce(c)}});return Object.freeze(a)}function Uf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function wc(r){let t=Uf(r);return t+Math.ceil(t/2)}function Of(r,t,e=!1){let n=r.length,o=Uf(t),s=wc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Ce(r):je(r),a=Q(i,t-st)+st;return e?gr(a,o):Ze(a,o)}var Ff=BigInt(0),ns=BigInt(1);function bc(r,t){let e=t.negate();return r?e:t}function Vf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function xc(r,t){Vf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function c0(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function l0(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))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,t){return{constTimeNegate:bc,hasPrecomputes(e){return Ec(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Ff;)n&ns&&(o=o.add(s)),s=s.double(),n>>=ns;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=xc(n,t),i=[],a=e,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(e,n,o){let{windows:s,windowSize:i}=xc(e,t),a=r.ZERO,c=r.BASE,u=BigInt(2**e-1),f=2**e,l=BigInt(e);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(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=xc(e,t),c=BigInt(2**e-1),u=2**e,f=BigInt(e);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(e,n,o){let s=vc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&vc.set(n,o(s))),s},wNAFCached(e,n,o){let s=Ec(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Ec(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Vf(n,t),Hf.set(e,n),vc.delete(e)}}}function ss(r,t,e,n){if(c0(e,r),l0(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=dc(BigInt(e.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((t.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(e[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),he(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 se=BigInt(0),$t=BigInt(1),is=BigInt(2),u0=BigInt(8),f0={zip215:!0};function h0(r){let t=Hn(r);return he(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Kf(r){let t=h0(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=is<<BigInt(a*8)-$t,f=e.create,l=Xe(t.n,t.nBitLength),d=t.uvRatio||((S,E)=>{try{return{isValid:!0,value:e.sqrt(S*e.inv(E))}}catch{return{isValid:!1,value:se}}}),h=t.adjustScalarBytes||(S=>S),p=t.domain||((S,E,C)=>{if(oe("phflag",C),E.length||C)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){qt("coordinate "+S,E,se,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:e.inv(M));let K=f(C*E),$=f(L*E),O=f(M*E);if(U)return{x:se,y:$t};if(O!==$t)throw new Error("invZ was invalid");return{x:K,y:$}}),b=yr(S=>{let{a:E,d:C}=t;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),nt=f(J*J),bt=f($*E),xt=f(J*f(bt+O)),Et=f(nt+f(C*f($*O)));if(xt!==Et)throw new Error("bad point: equation left != right (1)");let Bt=f(L*M),Kt=f(U*K);if(Bt!==Kt)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,$t,f(C*L))}static normalizeZ(E){let C=e.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),nt=f(L*$),bt=f(K*M);return O===J&&nt===bt}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=t,{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,nt=f(f(J*J)-U-K),bt=O+K,xt=bt-$,Et=O-K,Bt=f(nt*xt),Kt=f(bt*Et),Dt=f(nt*Et),fe=f(xt*bt);return new y(Bt,Kt,fe,Dt)}add(E){g(E);let{a:C,d:L}=t,{ex:M,ey:U,ez:K,et:$}=this,{ex:O,ey:J,ez:nt,et:bt}=E;if(C===BigInt(-1)){let Yu=f((U-M)*(J+O)),Ju=f((U+M)*(J-O)),za=f(Ju-Yu);if(za===se)return this.double();let Qu=f(K*is*bt),tf=f($*is*nt),ef=tf+Qu,rf=Ju+Yu,nf=tf-Qu,vm=f(ef*za),Em=f(rf*nf),Am=f(ef*nf),Sm=f(za*rf);return new y(vm,Em,Sm,Am)}let xt=f(M*O),Et=f(U*J),Bt=f($*L*bt),Kt=f(K*nt),Dt=f((M+U)*(O+J)-xt-Et),fe=Kt-Bt,be=Kt+Bt,Tn=f(Et-C*xt),ym=f(Dt*fe),wm=f(be*Tn),bm=f(Dt*Tn),xm=f(fe*be);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;qt("scalar",C,$t,n);let{p:L,f:M}=this.wNAF(C);return y.normalizeZ([L,M])[0]}multiplyUnsafe(E,C=y.ZERO){let L=E;return qt("scalar",L,se,n),L===se?A:this.is0()||L===$t?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}=t;return E===$t?this:this.multiplyUnsafe(E)}static fromHex(E,C=!1){let{d:L,a:M}=t,U=e.BYTES;E=at("pointHex",E,U),oe("zip215",C);let K=E.slice(),$=E[U-1];K[U-1]=$&-129;let O=je(K),J=C?u:e.ORDER;qt("pointHex.y",O,se,J);let nt=f(O*O),bt=f(nt-$t),xt=f(L*nt-M),{isValid:Et,value:Bt}=d(bt,xt);if(!Et)throw new Error("Point.fromHex: invalid y coordinate");let Kt=(Bt&$t)===$t,Dt=($&128)!==0;if(!C&&Bt===se&&Dt)throw new Error("Point.fromHex: x=0 and x_0=1");return Dt!==Kt&&(Bt=f(-Bt)),y.fromAffine({x:Bt,y:O})}static fromPrivateKey(E){return k(E).point}toRawBytes(){let{x:E,y:C}=this.toAffine(),L=gr(C,e.BYTES);return L[L.length-1]|=E&$t?128:0,L}toHex(){return Be(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,$t,f(t.Gx*t.Gy)),y.ZERO=new y(se,$t,$t,se);let{BASE:x,ZERO:A}=y,_=os(y,a*8);function v(S){return Q(S,n)}function B(S){return v(je(S))}function k(S){let E=e.BYTES;S=at("private key",S,E);let C=at("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=Ie(...E);return B(s(p(C,at("context",S),!!o)))}function V(S,E,C={}){S=at("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);qt("signature.s",J,se,n);let nt=Ie($,gr(J,e.BYTES));return at("result",nt,e.BYTES*2)}let D=f0;function I(S,E,C,L=D){let{context:M,zip215:U}=L,K=e.BYTES;S=at("signature",S,2*K),E=at("message",E),C=at("publicKey",C,K),U!==void 0&&oe("zip215",U),o&&(E=o(E));let $=je(S.slice(K,2*K)),O,J,nt;try{O=y.fromHex(C,U),J=y.fromHex(S.slice(0,K),U),nt=x.multiplyUnsafe($)}catch{return!1}if(!U&&O.isSmallOrder())return!1;let bt=H(M,J.toRawBytes(),O.toRawBytes(),E);return J.add(O.multiplyUnsafe(bt)).subtract(nt).clearCofactor().equals(y.ZERO)}return x._setWindowSize(8),{CURVE:t,getPublicKey:Y,sign:V,verify:I,ExtendedPoint:y,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(e.BYTES),precompute(S=8,E=y.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var Ac=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),qf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),q1=BigInt(0),d0=BigInt(1),$f=BigInt(2),$1=BigInt(3),p0=BigInt(5),m0=BigInt(8);function g0(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ac,a=r*r%s*r%s,c=it(a,$f,s)*a%s,u=it(c,d0,s)*r%s,f=it(u,p0,s)*u%s,l=it(f,t,s)*f%s,d=it(l,e,s)*l%s,h=it(d,n,s)*d%s,p=it(h,o,s)*h%s,m=it(p,o,s)*h%s,g=it(m,t,s)*f%s;return{pow_p_5_8:it(g,$f,s)*r%s,b2:a}}function y0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function w0(r,t){let e=Ac,n=Q(t*t*t,e),o=Q(n*n*t,e),s=g0(r*o).pow_p_5_8,i=Q(r*n*s,e),a=Q(t*i*i,e),c=i,u=Q(i*qf,e),f=a===r,l=a===Q(-r,e),d=a===Q(-r*qf,e);return f&&(i=c),(l||d)&&(i=u),Mf(i,e)&&(i=Q(-i,e)),{isValid:f||l,value:i}}var b0=Xe(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(),t=Kn.getPublicKey(r);return{privateKey:v0(r,t),publicKey:t}}function Gf(r,t){let e=r.subarray(0,Sc);return Kn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Wf(r,t,e){return Kn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function v0(r,t){let e=new Uint8Array(cs);for(let n=0;n<Sc;n++)e[n]=r[n],e[Sc+n]=t[n];return e}var qn=class{type="Ed25519";raw;constructor(t){this.raw=us(t,as)}toMultihash(){return Se.digest(de(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return Wf(this.raw,e,t)}},ls=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=us(t,cs),this.publicKey=new qn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return Gf(this.raw,t)}};function _c(r){return r=us(r,as),new qn(r)}async function Zf(){let{privateKey:r,publicKey:t}=zf();return new ls(r,t)}function us(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function ft(r=0){return new Uint8Array(r)}function Ct(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,It=127;function pt(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,t,e=0){switch(pt(r)){case 8:t[e++]=r&255|X,r/=128;case 7:t[e++]=r&255|X,r/=128;case 6:t[e++]=r&255|X,r/=128;case 5:t[e++]=r&255|X,r/=128;case 4:t[e++]=r&255|X,r>>>=7;case 3:t[e++]=r&255|X,r>>>=7;case 2:t[e++]=r&255|X,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function _0(r,t,e=0){switch(pt(r)){case 8:t.set(e++,r&255|X),r/=128;case 7:t.set(e++,r&255|X),r/=128;case 6:t.set(e++,r&255|X),r/=128;case 5:t.set(e++,r&255|X),r/=128;case 4:t.set(e++,r&255|X),r>>>=7;case 3:t.set(e++,r&255|X),r>>>=7;case 2:t.set(e++,r&255|X),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Lc(r,t){let e=r[t],n=0;if(n+=e&It,e<X||(e=r[t+1],n+=(e&It)<<7,e<X)||(e=r[t+2],n+=(e&It)<<14,e<X)||(e=r[t+3],n+=(e&It)<<21,e<X)||(e=r[t+4],n+=(e&It)*Bc,e<X)||(e=r[t+5],n+=(e&It)*Cc,e<X)||(e=r[t+6],n+=(e&It)*Ic,e<X)||(e=r[t+7],n+=(e&It)*kc,e<X))return n;throw new RangeError("Could not decode varint")}function B0(r,t){let e=r.get(t),n=0;if(n+=e&It,e<X||(e=r.get(t+1),n+=(e&It)<<7,e<X)||(e=r.get(t+2),n+=(e&It)<<14,e<X)||(e=r.get(t+3),n+=(e&It)<<21,e<X)||(e=r.get(t+4),n+=(e&It)*Bc,e<X)||(e=r.get(t+5),n+=(e&It)*Cc,e<X)||(e=r.get(t+6),n+=(e&It)*Ic,e<X)||(e=r.get(t+7),n+=(e&It)*kc,e<X))return n;throw new RangeError("Could not decode varint")}function kt(r,t,e=0){return t==null&&(t=Ct(pt(r))),t instanceof Uint8Array?Tc(r,t,e):_0(r,t,e)}function ie(r,t=0){return r instanceof Uint8Array?Lc(r,t):B0(r,t)}var Nc=new Float32Array([-0]),Ye=new Uint8Array(Nc.buffer);function Xf(r,t,e){Nc[0]=r,t[e]=Ye[0],t[e+1]=Ye[1],t[e+2]=Ye[2],t[e+3]=Ye[3]}function Yf(r,t){return Ye[0]=r[t],Ye[1]=r[t+1],Ye[2]=r[t+2],Ye[3]=r[t+3],Nc[0]}var Pc=new Float64Array([-0]),Tt=new Uint8Array(Pc.buffer);function Jf(r,t,e){Pc[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Qf(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],Pc[0]}var C0=BigInt(Number.MAX_SAFE_INTEGER),I0=BigInt(Number.MIN_SAFE_INTEGER),jt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return xr;if(t<C0&&t>I0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>th&&(o=0n,++n>th&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return xr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):xr}},xr=new jt(0,0);xr.toBigInt=function(){return 0n};xr.zzEncode=xr.zzDecode=function(){return this};xr.length=function(){return 1};var th=4294967296n;function eh(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function rh(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Dc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ae(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function fs(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Rc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ae(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ae(this,4);return fs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ae(this,4);return fs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ae(this,4);let t=Yf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ae(this,4);let t=Qf(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ae(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return rh(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ae(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ae(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new jt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ae(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ae(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ae(this,8);let t=fs(this.buf,this.pos+=4),e=fs(this.buf,this.pos+=4);return new jt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Lc(this.buf,this.pos);return this.pos+=pt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Mc(r){return new Rc(r instanceof Uint8Array?r:r.subarray())}function Mt(r,t,e){let n=Mc(r);return t.decode(n,void 0,e)}var Uc={};Rt(Uc,{base10:()=>k0});var k0=$e({prefix:"9",name:"base10",alphabet:"0123456789"});var Oc={};Rt(Oc,{base16:()=>T0,base16upper:()=>L0});var T0=lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L0=lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Fc={};Rt(Fc,{base2:()=>N0});var N0=lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vc={};Rt(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,t,e)=>(r[e]=t,r),[]),D0=oh.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function R0(r){return r.reduce((t,e)=>(t+=P0[e],t),"")}function M0(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=D0[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var U0=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:R0,decode:M0});var qc={};Rt(qc,{base64:()=>Hc,base64pad:()=>O0,base64url:()=>Kc,base64urlpad:()=>F0});var Hc=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O0=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Kc=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),F0=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $c={};Rt($c,{base8:()=>V0});var V0=lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zc={};Rt(zc,{identity:()=>H0});var H0=Gr({prefix:"\0",name:"identity",encode:r=>ff(r),decode:r=>uf(r)});var Av=new TextEncoder,Sv=new TextDecoder;var jc={};Rt(jc,{sha256:()=>en,sha512:()=>$0});function Wc({name:r,code:t,encode:e}){return new Gc(r,t,e)}var Gc=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?ee(this.code,e):e.then(n=>ee(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ih(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var en=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,...ec,...qc,...Vc},Mv={...jc,...ic};function ch(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},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 t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Ct(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),z0={utf8:ah,"utf-8":ah,hex:$n.base16,latin1:Zc,ascii:Zc,binary:Zc,...$n},hs=z0;function P(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Xc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Ct(i);o+i>t&&(n=Ct(t),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(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Yc(){}var Qc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},G0=Xc();function W0(r){return globalThis.Buffer!=null?Ct(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(t,e,n){return this.tail=this.tail.next=new vr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new tl((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ds,10,jt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=jt.fromBigInt(t);return this._push(ds,e.length(),e)}uint64Number(t){return this._push(Tc,pt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=jt.fromBigInt(t).zzEncode();return this._push(ds,e.length(),e)}sint64Number(t){let e=jt.fromNumber(t).zzEncode();return this._push(ds,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Jc,1,t?1:0)}fixed32(t){return this._push(zn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=jt.fromBigInt(t);return this._push(zn,4,e.lo)._push(zn,4,e.hi)}fixed64Number(t){let e=jt.fromNumber(t);return this._push(zn,4,e.lo)._push(zn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Xf,4,t)}double(t){return this._push(Jf,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Jc,1,0):this.uint32(e)._push(Z0,e,t)}string(t){let e=eh(t);return e!==0?this.uint32(e)._push(Dc,e,t):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 t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=W0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Jc(r,t,e){t[e]=r&255}function j0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var tl=class extends vr{next;constructor(t,e){super(j0,t,e),this.next=void 0}};function ds(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function zn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Z0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Gn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(X0,t,r),this},Gn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Y0,t,r),this});function X0(r,t,e){t.set(r,e)}function Y0(r,t,e){r.length<40?Dc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function el(){return new Gn}function Ut(r,t){let e=el();return t.encode(r,e,{lengthDelimited:!1}),e.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,t,e,n){return{name:r,type:t,encode:e,decode:n}}function rl(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return ps("enum",rn.VARINT,e,n)}function Ot(r,t){return ps("message",rn.LENGTH_DELIMITED,r,t)}var Er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Wn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var yt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(yt||(yt={}));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)})(yt||(yt={}));var pe;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),yt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=yt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(pe||(pe={}));var ol;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),yt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=yt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(ol||(ol={}));var oo={};Rt(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,...t){if(!J0(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function il(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function uh(r,t){sl(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var gs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ce=(r,t)=>r<<32-t|r>>>t;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 t=n=>r().update(al(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}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 ty(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var dh=(r,t,e)=>r&t^~r&e,ph=(r,t,e)=>r&t^r&e^t&e,ys=class extends ms{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=gs(this.buffer)}update(t){il(this);let{view:e,buffer:n,blockLen:o}=this;t=al(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){il(this),uh(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;ty(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var ey=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]),Je=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qe=new Uint32Array(64),cl=class extends ys{constructor(){super(64,32,8,!1),this.A=Je[0]|0,this.B=Je[1]|0,this.C=Je[2]|0,this.D=Je[3]|0,this.E=Je[4]|0,this.F=Je[5]|0,this.G=Je[6]|0,this.H=Je[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)Qe[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Qe[l-15],h=Qe[l-2],p=ce(d,7)^ce(d,18)^d>>>3,m=ce(h,17)^ce(h,19)^h>>>10;Qe[l]=m+Qe[l-7]+p+Qe[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=ce(a,6)^ce(a,11)^ce(a,25),h=f+d+dh(a,c,u)+ey[l]+Qe[l]|0,m=(ce(n,2)^ce(n,13)^ce(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(){Qe.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,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function tr(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*t);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function vs(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function 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 t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Sr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Sr(s,8)-n}function gh(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function yh(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function zt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var _2=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 t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Pe(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Zn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return fl(this.items)}},jn=[new Uint8Array([1])],wh="0123456789";var cn="",le=new ArrayBuffer(0),hl=new Uint8Array(0),Xn="EndOfContent",xh="OCTET STRING",vh="BIT STRING";function De(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):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(!Pe(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",le)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Te=class{constructor({blockLength:t=0,error:e=cn,warnings:n=[],valueBeforeDecode:o=hl}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Te.NAME="baseBlock";var Lt=class extends Te{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var As=class extends De(Te){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?q.BufferSourceConverter.toUint8Array(t.valueHex):hl,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",le}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=tr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};As.NAME="identificationBlock";var Ss=class extends Te{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Sr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=tr(this.length,8);if(o.byteLength>127)return this.error="Too big length",le;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Ss.NAME="lengthBlock";var T={},At=class extends Te{constructor({name:t=cn,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new As(o),this.lenBlock=new Ss(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new Zn;e||Eh(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?le:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return yh(e,n)}};At.NAME="BaseBlock";function Eh(r){if(r instanceof T.Constructed)for(let t of r.valueBlock.value)Eh(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var _s=class extends At{constructor({value:t=cn,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};_s.NAME="BaseStringBlock";var Bs=class extends De(Lt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Bs.NAME="PrimitiveValueBlock";var Ah,Cs=class extends At{constructor(t={}){super(t,Bs),this.idBlock.isConstructed=!1}};Ah=Cs;T.Primitive=Ah;Cs.NAME="PRIMITIVE";function uy(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function ai(r,t=0,e=r.length){let n=t,o=new At({},Lt),s=new Te;if(!Pe(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=At;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=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,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function dl(r){if(!r.byteLength){let t=new At({},Lt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ai(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function fy(r,t){return r?1:t}var me=class extends Lt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;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(t,e){let n=e||new Zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?le:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};me.NAME="ConstructedValueBlock";var Sh,er=class extends At{constructor(t={}){super(t,me),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
|
3
3
|
`).map(o=>` ${o}`).join(`
|
|
4
4
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
|
5
5
|
${t.join(`
|
|
6
|
-
`)}`:`${e} :`}};Sh=er;T.Constructed=Sh;er.NAME="CONSTRUCTED";var Is=class extends Lt{fromBER(t,e,n){return e}toBER(t){return le}};Is.override="EndOfContentValueBlock";var _h,ks=class extends At{constructor(t={}){super(t,Is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_h=ks;T.EndOfContent=_h;ks.NAME=Xn;var Bh,nn=class extends At{constructor(t={}){super(t,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Bh=nn;T.Null=Bh;nn.NAME="NULL";var Ts=class extends Re(Lt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);return Pe(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,cl.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="BooleanValueBlock";var Ch,Ls=class extends At{constructor(t={}){super(t,Ts),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ch=Ls;T.Boolean=Ch;Ls.NAME="BOOLEAN";var Ns=class extends Re(me){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=me.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===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(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?me.prototype.toBER.call(this,t,e):t?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 At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ns),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=ai(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return q.BufferSourceConverter.concat(t)}};Ih=Ps;T.OctetString=Ih;Ps.NAME=xh;var Rs=class extends Re(me){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=me.prototype.fromBER.call(this,t,e,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(t);if(!Pe(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=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,e+n}toBER(t,e){if(this.isConstructed)return me.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return le;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Rs.NAME="BitStringValueBlock";var kh,on=class extends At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return er.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};kh=on;T.BitString=kh;on.NAME=vh;var Th;function hy(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+e[0];break;default:u=s[i-l]+e[0]}switch(e[0]=u/10,!0){case l>=s.length:s=vs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return e[0]>0&&(s=vs(e,s)),s}function bh(r){if(r>=jn.length)for(let t=jn.length;t<=r;t++){let e=new Uint8Array([0]),n=jn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=vs(e,n)),jn.push(n)}return jn[r]}function dy(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-e,!0){case u<0:e=1,s[i-f]=u+10;break;default:e=0,s[i-f]=u}if(e>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-e,u<0)e=1,s[i-f]=u+10;else{e=0,s[i-f]=u;break}return s.slice()}var Yn=class extends Re(Lt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=cl.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gh(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case t:e=dy(bh(n),e),i="-";break;default:e=hy(e,bh(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=wh.charAt(e[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,St=class r extends At{constructor(t={}){super(t,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Es(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Es();let e=BigInt(t),n=new Zn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+e,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Lh=St;T.Integer=Lh;St.NAME="INTEGER";var Nh,Ds=class extends St{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Nh=Ds;T.Enumerated=Nh;Ds.NAME="ENUMERATED";var Jn=class extends Re(Lt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Es();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=tr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",le;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Jn.NAME="sidBlock";var Ms=class extends Lt{constructor({value:t=an,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Jn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,le;e.push(o)}return ll(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new 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 t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ms.NAME="ObjectIdentifierValueBlock";var Ph,sn=class extends At{constructor(t={}){super(t,Ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ph=sn;T.ObjectIdentifier=Ph;sn.NAME="OBJECT IDENTIFIER";var Qn=class extends Re(Te){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=tr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",le;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=q.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Qn.NAME="relativeSidBlock";var Us=class extends Lt{constructor({value:t=an,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Qn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,le;n.push(s)}return ll(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new Qn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Us.NAME="RelativeObjectIdentifierValueBlock";var Rh,Os=class extends At{constructor(t={}){super(t,Us),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Rh=Os;T.RelativeObjectIdentifier=Rh;Os.NAME="RelativeObjectIdentifier";var Dh,Le=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Dh=Le;T.Sequence=Dh;Le.NAME="SEQUENCE";var Mh,Fs=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Mh=Fs;T.Set=Mh;Fs.NAME="SET";var Vs=class extends Re(Lt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=an}toJSON(){return{...super.toJSON(),value:this.value}}};Vs.NAME="StringValueBlock";var Hs=class extends Vs{};Hs.NAME="SimpleStringValueBlock";var Ft=class extends _s{constructor({...t}={}){super(t,Hs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ft.NAME="SIMPLE STRING";var Ks=class extends Ft{fromBuffer(t){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=q.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ks.NAME="Utf8StringValueBlock";var Uh,Ne=class extends Ks{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Uh=Ne;T.Utf8String=Uh;Ne.NAME="UTF8String";var qs=class extends Ft{fromBuffer(t){this.valueBlock.value=q.Convert.ToUtf16String(t),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(t))}};qs.NAME="BmpStringValueBlock";var Oh,$s=class extends qs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Oh=$s;T.BmpString=Oh;$s.NAME="BMPString";var zs=class extends Ft{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=tr(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};zs.NAME="UniversalStringValueBlock";var Fh,Gs=class extends zs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Fh=Gs;T.UniversalString=Fh;Gs.NAME="UniversalString";var Vh,Ws=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Vh=Ws;T.NumericString=Vh;Ws.NAME="NumericString";var Hh,js=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Hh=js;T.PrintableString=Hh;js.NAME="PrintableString";var Kh,Zs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Kh=Zs;T.TeletexString=Kh;Zs.NAME="TeletexString";var qh,Xs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};qh=Xs;T.VideotexString=qh;Xs.NAME="VideotexString";var $h,Ys=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};$h=Ys;T.IA5String=$h;Ys.NAME="IA5String";var zh,Js=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};zh=Js;T.GraphicString=zh;Js.NAME="GraphicString";var Gh,to=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gh=to;T.VisibleString=Gh;to.NAME="VisibleString";var Wh,Qs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Wh=Qs;T.GeneralString=Wh;Qs.NAME="GeneralString";var jh,ti=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};jh=ti;T.CharacterString=jh;ti.NAME="CharacterString";var Zh,eo=class extends to{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=zt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=zt(this.month,2),e[2]=zt(this.day,2),e[3]=zt(this.hour,2),e[4]=zt(this.minute,2),e[5]=zt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Zh=eo;T.UTCTime=Zh;eo.NAME="UTCTime";var Xh,ei=class extends eo{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let l=new Number(t[t.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(zt(this.year,4)),e.push(zt(this.month,2)),e.push(zt(this.day,2)),e.push(zt(this.hour,2)),e.push(zt(this.minute,2)),e.push(zt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(zt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Xh=ei;T.GeneralizedTime=Xh;ei.NAME="GeneralizedTime";var Yh,ri=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Yh=ri;T.DATE=Yh;ri.NAME="DATE";var Jh,ni=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Jh=ni;T.TimeOfDay=Jh;ni.NAME="TimeOfDay";var Qh,oi=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Qh=oi;T.DateTime=Qh;oi.NAME="DateTime";var td,si=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};td=si;T.Duration=td;si.NAME="Duration";var ed,ii=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ed=ii;T.TIME=ed;ii.NAME="TIME";function et(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function cn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return hh(r)}var ro=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},no=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ci=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var rd={get(r=globalThis){let t=r.crypto;if(t?.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 t}};var rr=rd;async function nd(r){let t=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"]),e=await my(t);return{privateKey:e[0],publicKey:e[1]}}async function od(r,t){let e=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"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function sd(r,t,e){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,t,e instanceof Uint8Array?e:e.subarray())}async function my(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([rr.get().subtle.exportKey("jwk",r.privateKey),rr.get().subtle.exportKey("jwk",r.publicKey)])}function hl(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var ln=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return mt.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return sd(this._key,e,t)}},so=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return od(this._key,t)}};var li=8192,dl=18;function id(r){let{result:t}=fl(r),e=t.valueBlock.value;return{n:ge(e[1]),e:ge(e[2]),d:ge(e[3]),p:ge(e[4]),q:ge(e[5]),dp:ge(e[6]),dq:ge(e[7]),qi:ge(e[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 D("JWK was missing components");let e=new Le({value:[new St({value:0}),St.fromBigInt(ye(P(r.n,"base64url"))),St.fromBigInt(ye(P(r.e,"base64url"))),St.fromBigInt(ye(P(r.d,"base64url"))),St.fromBigInt(ye(P(r.p,"base64url"))),St.fromBigInt(ye(P(r.q,"base64url"))),St.fromBigInt(ye(P(r.dp,"base64url"))),St.fromBigInt(ye(P(r.dq,"base64url"))),St.fromBigInt(ye(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ad(r){let{result:t}=fl(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ge(e[0]),e:ge(e[1])}}function pl(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let e=new Le({value:[new Le({value:[new sn({value:"1.2.840.113549.1.1.1"}),new nn]}),new on({valueHex:new Le({value:[St.fromBigInt(ye(P(r.n,"base64url"))),St.fromBigInt(ye(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ge(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return et(t,"base64url")}function ye(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function cd(r){let t=id(r);return ld(t)}function ml(r){let t=ad(r);if(hl(t)>li)throw new Vr("Key size is too large");let e=ws(pe.encode({Type:yt.RSA,Data:r})),n=ee(dl,e);return new ln(t,n)}function ld(r){if(hl(r)>li)throw new D("Key size is too large");let t=ud(r),e=ws(pe.encode({Type:yt.RSA,Data:pl(t.publicKey)})),n=ee(dl,e);return new so(t.privateKey,new ln(t.publicKey,n))}async function gl(r){if(r>li)throw new D("Key size is too large");let t=await nd(r),e=ws(pe.encode({Type:yt.RSA,Data:pl(t.publicKey)})),n=ee(dl,e);return new so(t.privateKey,new ln(t.publicKey,n))}function ud(r){if(r==null)throw new D("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),yl=class extends Jr{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:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)or[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=or[l-15],h=or[l-2],p=ne(d,7)^ne(d,18)^d>>>3,m=ne(h,17)^ne(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=ne(a,6)^ne(a,11)^ne(a,25),h=f+d+If(a,c,u)+yy[l]+or[l]|0,m=(ne(n,2)^ne(n,13)^ne(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 yl);var ui=class extends Yr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,_f(t);let n=On(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Xr(this),this.iHash.update(t),this}digestInto(t){Xr(this),Zr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wl=(r,t,e)=>new ui(r,t).update(e).digest();wl.create=(r,t)=>new ui(r,t);function hd(r){r.lowS!==void 0&&oe("lowS",r.lowS),r.prehash!==void 0&&oe("prehash",r.prehash)}function wy(r){let t=Hn(r);he(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:by,hexToBytes:xy}=es,De={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=De;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=dr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?dr(o.length/2|128):"";return dr(r)+s+o+t},decode(r,t){let{Err:e}=De,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=De;if(r<Me)throw new t("integer: negative integers are not allowed");let e=dr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=De;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return by(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=De,o=typeof r=="string"?xy(r):r;Qr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=De,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Me=BigInt(0),vt=BigInt(1),lE=BigInt(2),dd=BigInt(3),uE=BigInt(4);function vy(r){let t=wy(r),{Fp:e}=t,n=Xe(t.n,t.nBitLength),o=t.toBytes||((m,g,w)=>{let b=g.toAffine();return Ie(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let g=m.subarray(1),w=e.fromBytes(g.subarray(0,e.BYTES)),b=e.fromBytes(g.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(m){let{a:g,b:w}=t,b=e.sqr(m),y=e.mul(b,m);return e.add(e.add(y,e.mul(m,g)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Fn(m,vt,t.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:b,n:y}=t;if(g&&typeof m!="bigint"){if(We(m)&&(m=Be(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:Ce(at("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)),qt("private key",x,vt,y),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=gr((m,g)=>{let{px:w,py:b,pz:y}=m;if(e.eql(y,e.ONE))return{x:w,y:b};let x=m.is0();g==null&&(g=x?e.ONE:e.inv(y));let A=e.mul(w,g),_=e.mul(b,g),v=e.mul(y,g);if(x)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=gr(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=m.toAffine();if(!e.isValid(g)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),y=i(g);if(!e.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||!e.isValid(g))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:w,y:b}=g||{};if(!g||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let y=x=>e.eql(x,e.ZERO);return y(w)&&y(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let w=e.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(at("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(e.isOdd)return!e.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=e.eql(e.mul(w,_),e.mul(x,y)),B=e.eql(e.mul(b,_),e.mul(A,y));return v&&B}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:g,b:w}=t,b=e.mul(w,dd),{px:y,py:x,pz:A}=this,_=e.ZERO,v=e.ZERO,B=e.ZERO,k=e.mul(y,y),Y=e.mul(x,x),H=e.mul(A,A),V=e.mul(y,x);return V=e.add(V,V),B=e.mul(y,A),B=e.add(B,B),_=e.mul(g,B),v=e.mul(b,H),v=e.add(_,v),_=e.sub(Y,v),v=e.add(Y,v),v=e.mul(_,v),_=e.mul(V,_),B=e.mul(b,B),H=e.mul(g,H),V=e.sub(k,H),V=e.mul(g,V),V=e.add(V,B),B=e.add(k,k),k=e.add(B,k),k=e.add(k,H),k=e.mul(k,V),v=e.add(v,k),H=e.mul(x,A),H=e.add(H,H),k=e.mul(H,V),_=e.sub(_,k),B=e.mul(H,Y),B=e.add(B,B),B=e.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=e.ZERO,B=e.ZERO,k=e.ZERO,Y=t.a,H=e.mul(t.b,dd),V=e.mul(w,x),R=e.mul(b,A),I=e.mul(y,_),N=e.add(w,b),S=e.add(x,A);N=e.mul(N,S),S=e.add(V,R),N=e.sub(N,S),S=e.add(w,y);let E=e.add(x,_);return S=e.mul(S,E),E=e.add(V,I),S=e.sub(S,E),E=e.add(b,y),v=e.add(A,_),E=e.mul(E,v),v=e.add(R,I),E=e.sub(E,v),k=e.mul(Y,S),v=e.mul(H,I),k=e.add(v,k),v=e.sub(R,k),k=e.add(R,k),B=e.mul(v,k),R=e.add(V,V),R=e.add(R,V),I=e.mul(Y,I),S=e.mul(H,S),R=e.add(R,I),I=e.sub(V,I),I=e.mul(Y,I),S=e.add(S,I),V=e.mul(R,S),B=e.add(B,V),V=e.mul(E,S),v=e.mul(N,v),v=e.sub(v,V),V=e.mul(N,R),k=e.mul(E,k),k=e.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}=t;qt("scalar",g,Me,b);let y=d.ZERO;if(g===Me)return y;if(this.is0()||g===vt)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>Me||v>Me;)A&vt&&(B=B.add(Y)),v&vt&&(k=k.add(Y)),Y=Y.double(),A>>=vt,v>>=vt;return x&&(B=B.negate()),_&&(k=k.negate()),k=new d(e.mul(k.px,w.beta),k.py,k.pz),B.add(k)}multiply(g){let{endo:w,n:b}=t;qt("scalar",g,vt,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(e.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===Me||v===vt||!_.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}=t;if(g===vt)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}=t;return g===vt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(g=!0){return oe("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return oe("isCompressed",g),Be(this.toRawBytes(g))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,p=os(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Ey(r){let t=Hn(r);return he(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function pd(r){let t=Ey(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.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({...t,toBytes(I,N,S){let E=N.toAffine(),C=e.toBytes(E.x),L=Ie;return oe("isCompressed",S),S?L(Uint8Array.from([N.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,e.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=Ce(E);if(!Fn(C,vt,e.ORDER))throw new Error("Point is not on curve");let L=f(C),M;try{M=e.sqrt(L)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let U=(M&vt)===vt;return(S&1)===1!==U&&(M=e.neg(M)),{x:C,y:M}}else if(N===s&&S===4){let C=e.fromBytes(E.subarray(0,e.BYTES)),L=e.fromBytes(E.subarray(e.BYTES,2*e.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=>Be(Ze(I,t.nByteLength));function h(I){let N=n>>vt;return I>N}function p(I){return h(I)?i(-I):I}let m=(I,N,S)=>Ce(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=t.nByteLength;return N=at("compactSignature",N,S*2),new g(m(N,0,S),m(N,S,2*S))}static fromDER(N){let{r:S,s:E}=De.toSig(at("DER",N));return new g(S,E)}assertValidity(){qt("r",this.r,vt,n),qt("s",this.s,vt,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:S,s:E,recovery:C}=this,L=_(at("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let M=C===2||C===3?S+t.n:S;if(M>=e.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*$),nt=c.BASE.multiplyAndAddUnsafe(K,O,J);if(!nt)throw new Error("point at infinify");return nt.assertValidity(),nt}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return pr(this.toDERHex())}toDERHex(){return De.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return pr(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=gc(t.n);return Of(t.randomBytes(I),t.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=We(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=t.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=Ce(I),S=I.length*8-t.nBitLength;return S>0?N>>BigInt(S):N},_=t.bits2int_modN||function(I){return i(A(I))},v=Vn(t.nBitLength);function B(I){return qt("num < 2^"+t.nBitLength,I,Me,v),Ze(I,t.nByteLength)}function k(I,N,S=Y){if(["recovered","canonical"].some(xt=>xt in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:C}=t,{lowS:L,prehash:M,extraEntropy:U}=S;L==null&&(L=!0),I=at("msgHash",I),hd(S),M&&(I=at("prehashed msgHash",E(I)));let K=_(I),$=u(N),O=[B($),B(K)];if(U!=null&&U!==!1){let xt=U===!0?C(e.BYTES):U;O.push(at("extraEntropy",xt))}let J=Ie(...O),nt=K;function bt(xt){let Et=A(xt);if(!l(Et))return;let Bt=a(Et),Kt=c.BASE.multiply(Et).toAffine(),Rt=i(Kt.x);if(Rt===Me)return;let fe=i(Bt*i(nt+Rt*$));if(fe===Me)return;let be=(Kt.x===Rt?0:2)|Number(Kt.y&vt),Tn=fe;return L&&h(fe)&&(Tn=p(fe),be^=1),new g(Rt,Tn,be)}return{seed:J,k2sig:bt}}let Y={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function V(I,N,S=Y){let{seed:E,k2sig:C}=k(I,N,S),L=t;return hc(L.hash.outputLen,L.nByteLength,L.hmac)(E,C)}c.BASE._setWindowSize(8);function R(I,N,S,E=H){let C=I;N=at("msgHash",N),S=at("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"||We(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(be){if(!(be instanceof De.Err))throw be}!O&&U!=="der"&&(O=g.fromCompact(C))}J=c.fromHex(S)}catch{return!1}if(!O||L&&O.hasHighS())return!1;M&&(N=t.hash(N));let{r:nt,s:bt}=O,xt=_(N),Et=a(bt),Bt=i(xt*Et),Kt=i(nt*Et),Rt=c.BASE.multiplyAndAddUnsafe(J,Bt,Kt)?.toAffine();return Rt?i(Rt.x)===nt:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:x,sign:V,verify:R,ProjectivePoint:c,Signature:g,utils:w}}function Ay(r){return{hash:r,hmac:(t,...e)=>wl(r,t,sc(...e)),randomBytes:Yo}}function md(r,t){let e=n=>pd({...r,...Ay(n)});return Object.freeze({...e(t),create:e})}var wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),gd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Sy=BigInt(1),bl=BigInt(2),yd=(r,t)=>(r+t/bl)/t;function _y(r){let t=wd,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=it(f,e,t)*f%t,d=it(l,e,t)*f%t,h=it(d,bl,t)*u%t,p=it(h,o,t)*h%t,m=it(p,s,t)*p%t,g=it(m,a,t)*m%t,w=it(g,c,t)*g%t,b=it(w,a,t)*m%t,y=it(b,e,t)*f%t,x=it(y,i,t)*p%t,A=it(x,n,t)*u%t,_=it(A,bl,t);if(!xl.eql(xl.sqr(_),r))throw new Error("Cannot find square root");return _}var xl=Xe(wd,void 0,void 0,{sqrt:_y}),Yt=md({a:BigInt(0),b:BigInt(7),Fp:xl,n:gd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=gd,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Sy*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=yd(s*r,t),c=yd(-n*r,t),u=Q(r-a*e-c*o,t),f=Q(-a*n-c*s,t),l=u>i,d=f>i;if(l&&(u=t-u),d&&(f=t-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},fd),bE=BigInt(0);var xE=Yt.ProjectivePoint;function Vt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Ct(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function vl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function bd(r,t){let e=tn.digest(t instanceof Uint8Array?t:t.subarray());if(vl(e))return e.then(({digest:n})=>Yt.sign(n,r).toDERRawBytes()).catch(n=>{throw new ro(String(n))});try{return Yt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new ro(String(n))}}function xd(r,t,e){let n=tn.digest(e instanceof Uint8Array?e:e.subarray());if(vl(n))return n.then(({digest:o})=>Yt.verify(t,o,r)).catch(o=>{throw new no(String(o))});try{return Yt.verify(t,n.digest,r)}catch(o){throw new no(String(o))}}var io=class{type="secp256k1";raw;_key;constructor(t){this._key=Ad(t),this.raw=vd(this._key)}toMultihash(){return Se.digest(de(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return xd(this._key,e,t)}},fi=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Ed(t),this.publicKey=new io(e??Sd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return bd(this.raw,t)}};function El(r){return new io(r)}async function _d(){let r=By();return new fi(r)}function vd(r){return Yt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ed(r){try{return Yt.getPublicKey(r,!0),r}catch(t){throw new Ln(String(t))}}function Ad(r){try{return Yt.ProjectivePoint.fromHex(r),r}catch(t){throw new Vr(String(t))}}function Sd(r){try{return Yt.getPublicKey(r,!0)}catch(t){throw new Ln(String(t))}}function By(){return Yt.utils.randomPrivateKey()}async function Bd(r,t){if(r==="Ed25519")return Zf();if(r==="secp256k1")return _d();if(r==="RSA")return gl(t??2048);throw new qe}function un(r){let{Type:t,Data:e}=pe.decode(r),n=e??new Uint8Array;switch(t){case yt.RSA:return ml(n);case yt.Ed25519:return Ac(n);case yt.secp256k1:return El(n);default:throw new qe}}function Cd(r){let{Type:t,Data:e}=pe.decode(r.digest),n=e??new Uint8Array;switch(t){case yt.Ed25519:return Ac(n);case yt.secp256k1:return El(n);default:throw new qe}}function de(r){return pe.encode({Type:yt[r.type],Data:r.raw})}var Id=Symbol.for("nodejs.util.inspect.custom"),Cy=114,ao=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Uo]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return mt.createV1(Cy,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ut(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ut(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Id](){return`PeerId(${this.toString()})`}},co=class extends ao{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},lo=class extends ao{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},uo=class extends ao{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Iy=2336,fo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Se.digest(P(this.url))}[Id](){return`PeerId(${this.url})`}[Uo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return mt.createV1(Iy,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=et(t)),t.toString()===this.toString())}};var ky=114,kd=2336;function we(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=re(Z.decode(`z${r}`));else{if(t==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=re(t.decode(r))}return fn(e)}function Al(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 qe}function Td(r){return Al(r.publicKey)}function fn(r){if(Ly(r))return new co({multihash:r});if(Ty(r))try{let t=Cd(r);if(t.type==="Ed25519")return new lo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new uo({multihash:r,publicKey:t})}catch{let e=et(r.digest);return new fo(new URL(e))}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 t=et(r.multihash.digest);return new fo(new URL(t))}return fn(r.multihash)}function Ty(r){return r.code===Se.code}function Ly(r){return r.code===tn.code}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _l=fr(Nd(),1);var po=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Bl=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Pd=r=>globalThis.DOMException===void 0?new Bl(r):new DOMException(r),Rd=r=>{let t=r.reason===void 0?Pd("This operation was aborted."):r.reason;return t instanceof Error?t:Pd(t)};function mo(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Rd(d));let h=()=>{f(Rd(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(e===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 ${e} milliseconds`,f(l))},e),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Cl(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var go=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Cl(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var sr=class extends _l.default{#t;#e;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:go,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#b(){return this.#e||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#n===void 0){let e=this.#p-t;if(e<0)this.#s=this.#t?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},e)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#A;if(this.#b&&this.#x){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#t?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#h()}async#S(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=mo(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#S(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof po&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#o}get isPaused(){return this.#i}};function pi(r){let t=[Zt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Il=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(t=>({name:t.name,type:Zt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Zt[t.type],TTL:t.TTL??t.ttl??Il,data:t.data instanceof Uint8Array?et(t.data):t.data}))}}var Ry=4;function kl(r,t={}){let e=new sr({concurrency:t.queryConcurrency??Ry});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(o.types).forEach(a=>{s.append("type",Zt[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=mi(await a.json());return o.onProgress?.(new dt("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Dd(){return[kl("https://cloudflare-dns.com/dns-query"),kl("https://dns.google/resolve")]}var Od=fr(Ud(),1);var Tl=class{lru;constructor(t){this.lru=(0,Od.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return mi({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Zt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Il)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Fd(r){return new Tl(r)}var Dy=1e3,gi=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Fd(t.cacheSize??Dy),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Dd())}async query(t,e={}){let n=pi(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let f of u.Answer)this.cache.add(t,f);return u}catch(u){a.push(u),e.onProgress?.(new dt("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Zt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Zt||(Zt={}));function Vd(r={}){return new gi(r)}var yi=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hd=45,My=15,hn=new yi;function Ll(r){if(!(r.length>My))return hn.new(r).parseWith(()=>hn.readIPv4Addr())}function Nl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hd))return hn.new(r).parseWith(()=>hn.readIPv6Addr())}function wi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hd))return hn.new(r).parseWith(()=>hn.readIPAddr())}var cS=parseInt("0xFFFF",16),lS=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function dn(r){return!!Ll(r)}function pn(r){return!!Nl(r)}function bi(r){return!!wi(r)}var $d=dn,Hy=pn,Pl=function(r){let t=0;if(r=r.toString().trim(),$d(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Hy(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=$d(e[n]),i;s&&(i=Pl(e[n]),e[n]=et(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,et(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},zd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var mn={},Rl={},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 t=$y(...r);Rl[t.code]=t,mn[t.name]=t});function $y(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Rl[r]!=null)return Rl[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 GS=W("ip4"),WS=W("ip6"),jS=W("ipcidr");function Ol(r,t){switch(W(r).code){case 4:case 41:return Gy(t);case 42:return Ul(t);case 6:case 273:case 33:case 132:return jd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ul(t);case 421:return Xy(t);case 444:return Wd(t);case 445:return Wd(t);case 466:return Zy(t);case 481:return globalThis.encodeURIComponent(Ul(t));default:return et(t,"base16")}}function Fl(r,t){switch(W(r).code){case 4:return Gd(t);case 41:return Gd(t);case 42:return Ml(t);case 6:case 273:case 33:case 132:return Vl(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ml(t);case 421:return Wy(t);case 444:return Yy(t);case 445:return Jy(t);case 466:return jy(t);case 481:return Ml(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}var Dl=Object.values($n).map(r=>r.decoder),zy=function(){let r=Dl[0].or(Dl[1]);return Dl.slice(2).forEach(t=>r=r.or(t)),r}();function Gd(r){if(!bi(r))throw new Error("invalid ip address");return Pl(r)}function Gy(r){let t=zd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!bi(t))throw new Error("invalid ip address");return t}function Vl(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function jd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ml(r){let t=P(r),e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function Ul(r){let t=ie(r);if(r=r.slice(pt(t)),r.length!==t)throw new Error("inconsistent lengths");return et(r)}function Wy(r){let t;r[0]==="Q"||r[0]==="1"?t=re(Z.decode(`z${r}`)).bytes:t=mt.parse(r).multihash.bytes;let e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function jy(r){let t=zy.decode(r),e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function Zy(r){let t=ie(r),e=r.slice(pt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+et(e,"base64url")}function Xy(r){let t=ie(r),e=r.slice(pt(t));if(e.length!==t)throw new Error("inconsistent lengths");return et(e,"base58btc")}function Yy(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Wt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Vl(n);return Vt([e,o],e.length+o.length)}function Jy(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Wt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Vl(n);return Vt([e,o],e.length+o.length)}function Wd(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=et(t,"base32"),o=jd(e);return`${n}:${o}`}function Zd(r){r=Hl(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Yd("invalid address: "+r);if(a.path===!0){n=Hl(o.slice(s).join("/")),t.push([a.code,Fl(a.code,n)]),e.push([a.code,n]);break}let c=Fl(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ol(a.code,c)])}return{string:Xd(e),bytes:ql(t),tuples:t,stringTuples:e,path:n}}function Kl(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ie(r,o),i=pt(s),a=W(s),c=Qy(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Yd("Invalid address Uint8Array: "+et(r,"base16"));t.push([s,u]);let f=Ol(s,u);if(e.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Xd(e),tuples:t,stringTuples:e,path:n}}function Xd(r){let t=[];return r.map(e=>{let n=W(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Hl(t.join("/"))}function ql(r){return Vt(r.map(t=>{let e=W(t[0]),n=Uint8Array.from(kt(e.code));return t.length>1&&t[1]!=null&&(n=Vt([n,t[1]])),n}))}function Qy(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ie(t instanceof Uint8Array?t:Uint8Array.from(t));return e+pt(e)}}function Hl(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Yd(r){return new Error("Error parsing address: "+r)}var tw=Symbol.for("nodejs.util.inspect.custom"),zl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),ew=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],$l=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},xi=class r{bytes;#t;#e;#s;#a;[zl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Kl(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Zd(t)}else if(ir(t))e=Kl(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#s=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=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??""}`),ew.includes(h)&&(e=i.name,o=443,n=`${p??""}${s}`,t=h===f.code?6:4),(h===i.code||h===a.code)&&(e=W(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(e=W(h).name,n=`${p??""}${s}`,t=h===u.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},W(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>W(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#s.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(ql(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===mn.p2p.code&&t.push([n,o]),n===mn["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?et(Z.decode(`z${n}`),"base58btc"):et(mt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=gn.get(e.name);if(n==null)throw new $l(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>rt(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[tw](){return`Multiaddr(${this.#t})`}};var gn=new Map;function ir(r){return!!r?.[zl]}function rt(r){return new xi(r)}var rw=32,{code:nw}=W("dnsaddr"),Gl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},Sr=async function(t,e={}){let n=e.maxRecursiveDepth??rw;if(n===0)throw new Gl("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===nw)??[],i=await(e?.dns??Vd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Zt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=rt(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var ip=fr(sp(),1),Ai=ip.default;var lw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Sr}},transportManager:{faultTolerance:He.FATAL_ALL}};async function ap(r){let t=Ai(lw,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return t}function uw(r,t){try{if(typeof r=="string"&&r.length>0)return fw(r);if(typeof r=="number"&&isFinite(r))return t?.long?dw(r):hw(r);throw new Error("Value is not a string or number.")}catch(e){let n=pw(e)?`${e.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 t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var _i=uw;function hw(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function dw(r){let t=Math.abs(r);return t>=864e5?Si(r,t,864e5,"day"):t>=36e5?Si(r,t,36e5,"hour"):t>=6e4?Si(r,t,6e4,"minute"):t>=1e3?Si(r,t,1e3,"second"):`${r} ms`}function Si(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function pw(r){return typeof r=="object"&&r!==null&&"message"in r}function jl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=_i,e.destroy=u,Object.keys(r).forEach(f=>{e[f]=r[f]}),e.names=[],e.skips=[],e.formatters={};function t(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return e.colors[Math.abs(l)%e.colors.length]}e.selectColor=t;function e(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let w=m,b=Number(new Date),y=b-(l||b);w.diff=y,w.prev=l,w.curr=b,l=b,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=e.formatters[v];if(typeof B=="function"){let k=g[x];_=B.call(w,k),g.splice(x,1),x--}return _}),e.formatArgs.call(w,g),(w.log||e.log).apply(w,g)}return m.namespace=f,m.useColors=e.useColors(),m.color=e.selectColor(f),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(f)),p),set:g=>{d=g}}),typeof e.init=="function"&&e.init(m),m}function n(f,l){let d=e(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){e.save(f),e.namespaces=f,e.names=[],e.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?e.skips.push(new RegExp("^"+f.substr(1)+"$")):e.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...e.names.map(a),...e.skips.map(a).map(l=>"-"+l)].join(",");return e.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=e.skips.length;l<d;l++)if(e.skips[l].test(f))return!1;for(l=0,d=e.names.length;l<d;l++)if(e.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var 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 t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var 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(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var cp=jl({formatArgs:yw,save:bw,load:xw,useColors:gw,setupFormatters:Ew,colors:mw,storage:Bi,log:ww});var Gt=cp;Gt.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);Gt.formatters.t=r=>r==null?"undefined":Wt.baseEncode(r);Gt.formatters.m=r=>r==null?"undefined":Fc.baseEncode(r);Gt.formatters.p=r=>r==null?"undefined":r.toString();Gt.formatters.c=r=>r==null?"undefined":r.toString();Gt.formatters.k=r=>r==null?"undefined":r.toString();Gt.formatters.a=r=>r==null?"undefined":r.toString();Gt.formatters.e=r=>r==null?"undefined":lp(r.stack)??lp(r.message)??r.toString();function Aw(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ci(){return{forComponent(r){return Sw(r)}}}function Sw(r){let t=Aw(`${r}:trace`);return Gt.enabled(`${r}:trace`)&&Gt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Gt(`${r}:trace`)),Object.assign(Gt(r),{error:Gt(`${r}:error`),trace:t})}function lp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function _r(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function Ii(r){let t=re(Z.decode(`z${r}`));return fn(t)}var Ue=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return _r(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return _r(this.map.values(),t=>t.key)}values(){return _r(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Br=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return _r(this.set.entries(),t=>{let e=Ii(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Ii(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return _r(this.set.values(),t=>Ii(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var pp=Symbol.for("@achingbrain/uint8arraylist");function dp(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Ti(r){return!!r?.[pp]}var wt=class r{bufs;length;[pp]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ti(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ti(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=dp(this.bufs,t);return e.buf[e.index]}set(t,e){let n=dp(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ti(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Vt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Vt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ti(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Ct(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Ct(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Zl=64,ue=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Zl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ft(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ut(this.fp,t.fp):!1}};function Cr(r,t){return Math.floor(Math.random()*(t-r))+r}var Ir=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");let e=Cr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Xl={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,t){let e=Xl[t],n=mp[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Bw(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Xl[t],o=mp[t],s=r;for(;s.length>0;){let i=gp.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Yl(r,{size:t=32,utf8Buffer:e}={}){if(!Xl[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Bw(r,t,e);r=gp.encode(r)}return _w(r,t)}var Cw=fr(hp(),1);var wo={hash:r=>Number(Yl(r,{size:32})),hashV:(r,t)=>Iw(wo.hash(r,t))};function Iw(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var kw=500,bo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??wo,this.seed=t.seed??Cr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ir(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ir(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize));for(let a=0;a<kw;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},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,t=.001){let e=Lw(t),n=Tw[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Zl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Li=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??wo,this.seed=t.seed??Cr(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(t){if(typeof t=="string"&&(t=P(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new bo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Jl(r,t=.001,e){return new Li({...yp(r,t),...e??{}})}var xo;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ft(0),payloadType:ft(0),payload:ft(0),signature:ft(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(xo||(xo={}));var Ni=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var bn=class r{static createFromProtobuf=async t=>{let e=xo.decode(t),n=un(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=wp(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Ni("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=xo.encode({publicKey:de(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ut(this.marshal(),t.marshal())}async validate(t){let e=wp(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},wp=(r,t,e)=>{let n=P(r),o=kt(n.byteLength),s=kt(t.length),i=kt(e.length);return new wt(o,n,s,t,i,e)};function bp(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var xp="libp2p-peer-record",vp=Uint8Array.from([3,1]);var vo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Ot((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:ft(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=>Ut(s,n.codec()),n.decode=(s,i)=>Mt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Ot((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:ft(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 vr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Ut(n,r.codec()),r.decode=(n,o)=>Mt(n,r.codec(),o)})(vo||(vo={}));var kr=class r{static createFromProtobuf=t=>{let e=vo.decode(t),n=fn(re(e.peerId)),o=(e.addresses??[]).map(i=>rt(i.multiaddr)),s=e.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(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=vo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!bp(this.multiaddrs,t.multiaddrs))}};function Nw(r){return r[Symbol.asyncIterator]!=null}function Pw(r){if(Nw(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var Eo=Pw;var ar={},xn=r=>{r.addEventListener("message",t=>{xn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{xn.dispatchEvent("message",r,t)})};xn.addEventListener=(r,t)=>{ar[r]==null&&(ar[r]=[]),ar[r].push(t)};xn.removeEventListener=(r,t)=>{ar[r]!=null&&(ar[r]=ar[r].filter(e=>e===t))};xn.dispatchEvent=function(r,t,e){ar[r]!=null&&ar[r].forEach(n=>n(t,e))};var Ql=xn;var tu="lock:worker:request-read",eu="lock:worker:release-read",ru="lock:master:grant-read",nu="lock:worker:request-write",ou="lock:worker:release-write",su="lock:master:grant-write";var Ep=(r=21)=>Math.random().toString().substring(2);var Ap=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f?.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,t,e,n)=>async()=>{let o=Ep();return globalThis.postMessage({type:t,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===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},Rw={singleProcess:!1},_p=r=>{if(r=Object.assign({},Rw,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return Ql.addEventListener("message",Ap(e,"requestReadLock",tu,eu,ru)),Ql.addEventListener("message",Ap(e,"requestWriteLock",nu,ou,su)),e}return{isWorker:!0,readLock:e=>Sp(e,tu,ru,eu),writeLock:e=>Sp(e,nu,su,ou)}};var Tr={},cr;async function iu(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var Dw=(r,t)=>{if(cr.isWorker===!0)return{readLock:cr.readLock(r,t),writeLock:cr.writeLock(r,t)};let e=new sr({concurrency:1}),n;return{async readLock(){if(n!=null)return iu(n,t);n=new sr({concurrency:t.concurrency,autoStart:!1});let o=n,s=iu(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,iu(e,t)}}},Mw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function au(r){let t=Object.assign({},Mw,r);return cr==null&&(cr=_p(t),cr.isWorker!==!0&&(cr.addEventListener("requestReadLock",e=>{Tr[e.data.name]!=null&&Tr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),cr.addEventListener("requestWriteLock",async e=>{Tr[e.data.name]!=null&&Tr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Tr[t.name]==null&&(Tr[t.name]=Dw(t.name,t)),Tr[t.name]}var vn;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ot((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:ft(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=>Ut(i,o.codec()),o.decode=(i,a)=>Mt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ot((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),Ri.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=Ri.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Ut(i,o.codec()),o.decode=(i,a)=>Mt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ot((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 vr('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 vr('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=>Ut(o,r.codec()),r.decode=(o,s)=>Mt(o,r.codec(),s)})(vn||(vn={}));var Pi;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ft(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(Pi||(Pi={}));var Ri;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(Ri||(Ri={}));function En(r,t){let e=vn.decode(t);if(e.publicKey!=null&&r.publicKey==null){let s=un(e.publicKey);r=Al(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:r,addresses:e.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:rt(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}var Oe="/",Bp=new TextEncoder().encode(Oe),Di=Bp[0],Lr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Di)throw new Error("Invalid key")}toString(t="utf8"){return et(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Oe))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Bp),this._buf[0]!==Di){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Di,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Di;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Oe).slice(1)}type(){return Uw(this.baseNamespace())}name(){return Ow(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Oe)||(t+=Oe),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Oe):new r(t.slice(0,-1).join(Oe))}child(t){return this.toString()===Oe?t:t.toString()===Oe?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Fw(t.map(e=>e.namespaces()))])}};function Uw(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Ow(r){let t=r.split(":");return t[t.length-1]}function Fw(r){return[].concat(...r)}var cu="/peers/";function An(r){if(!Oo(r)||r.type==null)throw new D("Invalid PeerId");let t=r.toCID().toString();return new Lr(`${cu}${t}`)}async function Cp(r,t,e){let n=new Map;for(let o of e){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=rt(o.multiaddr)),!ir(o.multiaddr))throw new D("Multiaddr was invalid");if(!await t(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Ui(r,t,e,n){if(t==null)throw new D("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Mi(d,{validate:Ip})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Mi(d,{validate:kp,map:Tp})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Mi([...a.entries()],{validate:Ip})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Mi([...h.entries()],{validate:kp,map:Tp})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=de(o.id.publicKey):t.publicKey!=null?f=de(t.publicKey):r.publicKey!=null&&(f=de(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,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function Ip(r,t){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function kp(r,t){if(typeof r!="string")throw new D("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new D("Tag value must be an integer");if(t.value<0||t.value>100)throw new D("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new D("Tag ttl must be an integer");if(t.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function Tp(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Oi(r,t){let e=r.toString().split("/")[2],n=mt.parse(e,Wt),o=hi(n);return En(o,t)}function Vw(r){return r==null?{}:{prefix:cu,filters:(r.filters??[]).map(t=>({key:e,value:n})=>t(Oi(e,n))),orders:(r.orders??[]).map(t=>(e,n)=>t(Oi(e.key,e.value),Oi(n.key,n.value)))}}var Fi=class{peerId;datastore;lock;addressFilter;constructor(t,e={}){this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=au({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(An(t))}async delete(t){if(this.peerId.equals(t))throw new D("Cannot delete self peer");await this.datastore.delete(An(t))}async load(t){let e=await this.datastore.get(An(t));return En(t,e)}async save(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,s,n,o)}async patch(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async merge(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Vw(t??{}))){let o=Oi(e,n);o.id.equals(this.peerId)||(yield o)}}async#t(t){try{let e=await this.datastore.get(An(t)),n=En(t,e);return{existingBuf:e,existingPeer:n}}catch(e){if(e.name!=="NotFoundError")throw e}return{}}async#e(t,e,n,o){let s=vn.encode(e);return n!=null&&ut(s,n)?{peer:En(t,s),previous:o,updated:!1}:(await this.datastore.put(An(t),s),{peer:En(t,s),previous:o,updated:!0})}};var lu=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Fi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Eo(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await bn.openAndCertify(t,kr.DOMAIN),o=hi(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=kr.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=kr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function Lp(r,t={}){return new lu(r,t)}var Vi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function Hw(r){return r[Symbol.asyncIterator]!=null}function Kw(r){if(Hw(r))return(async()=>{for await(let t of r);})();for(let t of r);}var uu=Kw;function qw(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Np=qw;function $w(r){return r[Symbol.asyncIterator]!=null}function zw(r,t){let e=0;if($w(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Np(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var Nr=zw;function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r,t){return Gw(r)?async function*(){yield*(await Eo(r)).sort(t)}():function*(){yield*Eo(r).sort(t)}()}var fu=Ww;function jw(r){return r[Symbol.asyncIterator]!=null}function Zw(r,t){return jw(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var hu=Zw;var Hi=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await uu(this.putMany(t,n)),t=[],await uu(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=Nr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Nr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>fu(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=Nr(n,()=>o++>=s)}return t.limit!=null&&(n=hu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=Nr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Nr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>fu(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=Nr(n,()=>s++>=o)}return t.limit!=null&&(n=hu(n,t.limit)),n}};var Ki=class extends Hi{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new Vi;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new Lr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new Lr(t)}};function Pp(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Xw=r=>r;function du(r,t){let e=r.getPeerId();return e!=null&&we(e).equals(t)&&(r=r.decapsulate(rt(`/p2p/${t.toString()}`))),r}var pu=4,mu=41,Yw=54,Jw=55,Qw=6,tb=273,qi=class{log;components;listen;announce;appendAnnounce;observed;announceFilter;ipDomainMappings;publicAddressMappings;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.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=e.announceFilter??Xw,this._updatePeerStoreAddresses=Pp(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>rt(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>rt(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>rt(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>rt(t))}addObservedAddr(t){t=du(t,this.components.peerId);let e=t.toString();this.observed.has(e)||this.observed.set(e,{confident:!1})}confirmObservedAddr(t){t=du(t,this.components.peerId);let e=t.toString(),o=(this.observed.get(e)??{confident:!1}).confident;this.observed.set(e,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=du(t,this.components.peerId);let e=t.toString();this.observed.delete(e)}getAddresses(){let t=this.getAnnounceAddrs();t.length===0&&(t=this.components.transportManager.getAddrs()),t=t.concat(...this.getAppendAnnounceAddrs(),Array.from(this.observed).filter(([s,i])=>i.confident).map(([s])=>rt(s)));let e=[];t.forEach(s=>{let i=s.stringTuples(),a;if((i[0][0]===pu||i[0][0]===mu)&&i[1][0]===Qw?a=`${i[0][1]}-${i[1][1]}-tcp`:(i[0][0]===pu||i[0][0]===mu)&&i[1][0]===tb&&(a=`${i[0][1]}-${i[1][1]}-udp`),a==null)return;let c=this.publicAddressMappings.get(a);c?.forEach(u=>{i[0][1]=u.externalIp,i[1][1]=`${u.externalPort}`,e.push(rt(`/${i.map(f=>[W(f[0]).name,f[1]].join("/")).join("/")}`))})}),t=t.concat(e);let n=[];for(let s of t){let i=s.stringTuples(),a=!1;for(let[c,u]of this.ipDomainMappings.entries())for(let f=0;f<i.length;f++)i[f][1]===c&&(i[f][0]===pu&&(i[f][0]=Yw,i[f][1]=u,a=!0),i[f][0]===mu&&(i[f][0]=Jw,i[f][1]=u,a=!0));a&&n.push(rt(`/${i.map(c=>[W(c[0]).name,c[1]].join("/")).join("/")}`))}t=t.concat(n);let o=new Set;return t=t.filter(s=>{let i=s.toString();return o.has(i)?!1:(o.add(i),!0)}),this.announceFilter(Array.from(o).map(s=>{let i=rt(s);return i.protos().pop()?.path===!0||i.getPeerId()===this.components.peerId.toString()?i:i.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}addDNSMapping(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t),this.ipDomainMappings.set(n,t)}),this._updatePeerStoreAddresses()}removeDNSMapping(t){for(let[e,n]of this.ipDomainMappings.entries())n===t&&(this.log("remove DNS mapping for %s",t),this.ipDomainMappings.delete(e));this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.publicAddressMappings.get(i)??[];a.push({externalIp:n,externalPort:o}),this.publicAddressMappings.set(i,a),this._updatePeerStoreAddresses()}removePublicAddressMapping(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${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 Rp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Rp||(Rp={}));var $i=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},zi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},Sn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Ao=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Gi=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Wi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},ji=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},So=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Pr=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Zi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Xi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},Rr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Dr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Yi=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var gu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=Ci())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Wo(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},rb=["metrics","connectionProtector","dns"],nb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Dp(r={}){let t=new gu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!nb.includes(o)){let i=t.components[o];if(i==null&&!rb.includes(o))throw new $i(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function Mp(r){let t={};for(let e of Object.values(r.components))for(let n of ob(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of sb(e))if(t[n]!==!0)throw new zi(`Service "${ib(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function ob(r){return Array.isArray(r?.[Pn])?r[Pn]:[]}function sb(r){return Array.isArray(r?.[ja])?r[ja]:[]}function ib(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Op=fr(Up(),1),ab=["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"],cb=ab.map(r=>new Op.Netmask(r));function yu(r){for(let t of cb)if(t.contains(r))return!0;return!1}function lb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ub(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return yu(o)}function fb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function hb(r){let t=r.split(":"),e=t[t.length-1];return yu(e)}function db(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 Ji(r){return dn(r)?yu(r):lb(r)?ub(r):fb(r)?hb(r):pn(r)?db(r):void 0}var pb=r=>r.toString().split("/").slice(1),_n=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>_n(e=>e===r).match(t),pattern:r}),Mr=()=>({match:r=>_n(t=>typeof t=="string").match(r),pattern:"{string}"}),Bo=()=>({match:r=>_n(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),tt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{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{Vc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),j=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Pt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function ct(...r){function t(o){let s=pb(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ta=G(z("dns4"),Mr()),ea=G(z("dns6"),Mr()),ra=G(z("dnsaddr"),Mr()),bu=G(z("dns"),Mr()),M6=ct(ta,j(tt())),U6=ct(ea,j(tt())),O6=ct(ra,j(tt())),F6=ct(Pt(bu,ra,ta,ea),j(tt())),Fp=G(z("ip4"),_n(dn)),Vp=G(z("ip6"),_n(pn)),xu=Pt(Fp,Vp),Fe=Pt(xu,bu,ta,ea,ra),V6=ct(Pt(xu,G(Pt(bu,ra,ta,ea),j(tt())))),H6=ct(Fp),K6=ct(Vp),q6=ct(xu),vu=G(Fe,z("tcp"),Bo()),Io=G(Fe,z("udp"),Bo()),Eu=ct(G(vu,j(tt()))),$6=ct(Io),Au=G(Io,z("quic"),j(tt())),na=G(Io,z("quic-v1"),j(tt())),mb=Pt(Au,na),z6=ct(Au),G6=ct(na),wu=Pt(Fe,vu,Io,Au,na),Hp=Pt(G(wu,z("ws"),j(tt()))),ko=ct(Hp),Kp=Pt(G(wu,z("wss"),j(tt())),G(wu,z("tls"),j(G(z("sni"),Mr())),z("ws"),j(tt()))),Su=ct(Kp),qp=G(Io,z("webrtc-direct"),j(Co()),j(Co()),j(tt())),_u=ct(qp),$p=G(na,z("webtransport"),j(Co()),j(Co()),j(tt())),Bu=ct($p),Qi=Pt(Hp,Kp,G(vu,j(tt())),G(mb,j(tt())),G(Fe,j(tt())),qp,$p,tt()),W6=ct(Qi),gb=G(Qi,z("p2p-circuit"),tt()),To=ct(gb),yb=Pt(G(Qi,z("p2p-circuit"),z("webrtc"),j(tt())),G(Qi,z("webrtc"),j(tt())),G(z("webrtc"),j(tt()))),Cu=ct(yb),wb=Pt(G(Fe,z("tcp"),Bo(),z("http"),j(tt())),G(Fe,z("http"),j(tt()))),j6=ct(wb),bb=Pt(G(Fe,z("tcp"),Pt(G(z("443"),z("http")),G(Bo(),z("https"))),j(tt())),G(Fe,z("tls"),z("http"),j(tt())),G(Fe,z("https"),j(tt()))),Z6=ct(bb),xb=Pt(G(z("memory"),Mr(),j(tt()))),X6=ct(xb);var vb=4,Eb=41;function zp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(ko.matches(t))return!1;let e=t.stringTuples();return e[0][0]===vb||e[0][0]===Eb?!!Ji(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var Gp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Ab=new WeakMap;function Sb({clearTimeout:r,setTimeout:t}={}){return(e,{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=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Ab.set(l,()=>{c(s),s=null,i()}),l}}var _b=Sb(),Wp=_b;var oa=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},sa=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ia=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new Iu}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new oa("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(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},Iu=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function aa(r){if(Oo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:we(e),r.forEach(n=>{if(!ir(n))throw new Ke("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=we(o);if(t?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Bb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Bb;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var Zp="last-dial-failure",Xp="last-dial-success";var ca=100,la=50;var Yp={maxConnections:ca,allow:[]},ua=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??Yp.maxConnections,this.allow=e.allow??Yp.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new Ue;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await jp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var fa=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Bn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new fa(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new fa(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ku=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ha(r={}){return Cb(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Cb(r,t){t=t??{};let e=t.onEnd,n=new Bn,o,s,i,a=ht(),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=ht()})}},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(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new 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)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(g){return m.end(g),e!=null&&(e(g),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Tu=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Cn(r,t,e,n){let o=new Tu(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var da=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function lr(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new da(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new da(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var pa=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ib(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ma=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Ib(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ot(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(t={}){let e=new pa(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await lr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var In=class extends ve{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new sa;let n=new ma(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new te)}),this.clear()}async onEmpty(t){this.size!==0&&await Cn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Cn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Cn(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ha({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ga=class extends In{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ve(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var kb=4,Tb=41,Lb=53,Nb=54,Pb=55,Rb=56;function Lu(r){try{let[[t,e]]=r.stringTuples();if(e==null)return!0;if(t===Lb||t===Nb||t===Pb||t===Rb)return!1;if(t===kb||t===Tb)return Ji(e)??!1}catch{}return!0}function Db(r,t){let e=Eu.exactMatch(r.multiaddr),n=Eu.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Su.exactMatch(r.multiaddr),s=Su.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=ko.exactMatch(r.multiaddr),a=ko.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Cu.exactMatch(r.multiaddr),u=Cu.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=_u.exactMatch(r.multiaddr),l=_u.exactMatch(t.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=Bu.exactMatch(r.multiaddr),h=Bu.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function Mb(r,t){let e=Lu(r.multiaddr),n=Lu(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Ub(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Ob(r,t){let e=To.exactMatch(r.multiaddr),n=To.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Jp(r){return r.sort(Db).sort(Ub).sort(Ob).sort(Mb)}async function Qp(r,t){let e=!1;for(let o of gn.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}var ya={maxParallelDials:la,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Sr}},wa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??ya.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??ya.maxDialQueueLength,this.dialTimeout=e.dialTimeout??ya.dialTimeout,this.connections=e.connections??new Ue,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,ot(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(e.resolvers??{}))gn.set(n,o);this.queue=new ga({concurrency:e.maxParallelDials??ya.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==te.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,ot(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=aa(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new qr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new dt("dial-queue:start-dial"));let c=Ve([this.shutDownController.signal,a.signal]);ot(1/0,c);let u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new dt("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 qr("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:e.priority??Du,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(l=>({multiaddr:rt(l),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new qr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new So("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let l=await this.components.peerStore.get(t);o.push(...l.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let l=await this.components.peerRouting.findPeer(t);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",t,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await 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(t!=null){let l=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Pr("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",t??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!To.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ba=class extends In{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var im=fr(om(),1);var Vb=Object.prototype.toString,Hb=r=>Vb.call(r)==="[object Error]",Kb=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&&Hb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Kb.has(r.message):!1}var Uu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},sm=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Ou(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=im.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Uu)throw c.originalError;if(c instanceof TypeError&&!Mu(c))throw c;if(sm(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){sm(u,a,t),i(),n(u)}}})})}var xa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new ba({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.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(t){if(!this.started)return;let e=await this.peerStore.get(t);am(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Ou(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(Wa)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>am(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function am(r){for(let t of r.tags.keys())if(t.startsWith(Wa))return!0;return!1}var Du=50,Fu={maxConnections:ca,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},va=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Fu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new Ue,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>rt(n)),this.deny=(e.deny??[]).map(n=>rt(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Fu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ia({points:e.inboundConnectionThreshold??Fu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ua({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new wa(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??la,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??5e3,resolvers:e.resolvers??{dnsaddr:Sr},connections:this.connections}),this.reconnectQueue=new xa({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),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 t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),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:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.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:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new xe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=aa(t);if(this.peerId.equals(n))throw new Kr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Du});if(o.status!=="open")throw new Hr("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),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Ke("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>rt(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var kn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(t){this.timespan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timespan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var zb=1.2,Gb=2,Wb=2e3,Ea=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new kn(t.interval??5e3),this.failure=new kn(t.interval??5e3),this.next=new kn(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Gb,this.timeoutMultiplier=t.timeoutMultiplier??zb,this.minTimeout=t.minTimeout??Wb,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=Ve([t.signal,n]);return ot(1/0,o,n),o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var Vu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ht(),this.haveNext=ht()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ht(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ht(),await lr(this.readNext.promise,e?.signal,e)}};function cm(){return new Vu}var Aa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Hu=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ku=class extends Hu{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Sa(r,t){let e=cm();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new wt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new 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 wt:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new Aa("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var jb=1e4,Zb="1.0.0",Xb="ping",Yb="ipfs",lm=32,Jb=!0,_a=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Yb}/${Xb}/${Zb}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??jb,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Jb,this.timeout=new Ea({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Pn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,ot(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Sa(o);e=Date.now(),await Promise.all([s.write(cn(lm),{signal:n}),s.read(lm,{signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Qb(r){return r[Symbol.asyncIterator]!=null}function tx(...r){let t=[];for(let e of r)Qb(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=ha({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Lo=tx;var Ba=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");let n=this,o=new Br;for await(let s of Lo(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new xe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new xe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var Ca=globalThis.CustomEvent??Event;async function*qu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,s=[],i=ht(),a=ht(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=ht(),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 Ca("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new Ca("task-complete"))})}c=!0,o.dispatchEvent(new Ca("task-complete"))}catch(p){u=p,o.dispatchEvent(new Ca("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=ht(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var Ia=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new Ao("No peer routers available");if(t.toString()===this.peerId.toString())throw new Gi("Should not try to find self");let n=this,o=Lo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Vo}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Ao("No peer routers available");let n=this,o=Jl(1024);for await(let s of qu(async function*(){let i=Lo(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ka=class extends ve{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ot(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ot(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Ve([this.shutdownController.signal,t?.signal]);ot(1/0,e);try{for(;;)this.needNext?.resolve(),this.needNext=ht(),yield(await Cn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ot(1/0,this.walkController.signal);let t=Ve([this.walkController.signal,this.shutdownController.signal]);ot(1/0,t);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=cn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await lr(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var $u=32,zu=64,Ta=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Wi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t))throw new ji(`Handler already registered for protocol ${t}`);let o=Ai.bind({ignoreUndefined:!0})({maxInboundStreams:$u,maxOutboundStreams:zu},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,e){if(e==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Gu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function um(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Gu({name:t,metrics:e}):n=new Map,n}var La=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=um({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??He.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new D("Transport must have a valid tag");if(this.transports.has(e))throw new D(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new Yi(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new xe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(t),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){e.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==He.NO_FATAL)throw new Pr(`Transport (${n}) could not listen on any available address`)}if(e.length===this.transports.size){let n=`no valid addresses were provided for transports [${e.join(", ")}]`;if(this.faultTolerance===He.FATAL_ALL)throw new Pr(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var _t="/multistream/1.0.0";var Na=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ra=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function No(r,t={}){let e=Sa(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=pt(t.maxDataLength));let n=t?.lengthDecoder??ie,o=t?.lengthEncoder??kt;return{read:async i=>{let a=-1,c=new wt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Na("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ra("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Pa("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new wt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new wt(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var ex=P(`
|
|
7
|
-
`);async function
|
|
6
|
+
`)}`:`${e} :`}};Sh=er;T.Constructed=Sh;er.NAME="CONSTRUCTED";var Is=class extends Lt{fromBER(t,e,n){return e}toBER(t){return le}};Is.override="EndOfContentValueBlock";var _h,ks=class extends At{constructor(t={}){super(t,Is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_h=ks;T.EndOfContent=_h;ks.NAME=Xn;var Bh,on=class extends At{constructor(t={}){super(t,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Bh=on;T.Null=Bh;on.NAME="NULL";var Ts=class extends De(Lt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);return Pe(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,ul.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="BooleanValueBlock";var Ch,Ls=class extends At{constructor(t={}){super(t,Ts),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ch=Ls;T.Boolean=Ch;Ls.NAME="BOOLEAN";var Ns=class extends De(me){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=me.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===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(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?me.prototype.toBER.call(this,t,e):t?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 At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ns),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=ai(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return q.BufferSourceConverter.concat(t)}};Ih=Ps;T.OctetString=Ih;Ps.NAME=xh;var Ds=class extends De(me){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=me.prototype.fromBER.call(this,t,e,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(t);if(!Pe(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=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,e+n}toBER(t,e){if(this.isConstructed)return me.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return le;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 At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return er.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};kh=sn;T.BitString=kh;sn.NAME=vh;var Th;function hy(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+e[0];break;default:u=s[i-l]+e[0]}switch(e[0]=u/10,!0){case l>=s.length:s=vs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return e[0]>0&&(s=vs(e,s)),s}function bh(r){if(r>=jn.length)for(let t=jn.length;t<=r;t++){let e=new Uint8Array([0]),n=jn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=vs(e,n)),jn.push(n)}return jn[r]}function dy(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-e,!0){case u<0:e=1,s[i-f]=u+10;break;default:e=0,s[i-f]=u}if(e>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-e,u<0)e=1,s[i-f]=u+10;else{e=0,s[i-f]=u;break}return s.slice()}var Yn=class extends De(Lt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=ul.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gh(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case t:e=dy(bh(n),e),i="-";break;default:e=hy(e,bh(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=wh.charAt(e[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,St=class r extends At{constructor(t={}){super(t,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Es(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Es();let e=BigInt(t),n=new Zn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+e,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Lh=St;T.Integer=Lh;St.NAME="INTEGER";var Nh,Rs=class extends St{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Nh=Rs;T.Enumerated=Nh;Rs.NAME="ENUMERATED";var Jn=class extends De(Lt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Es();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=tr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",le;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Jn.NAME="sidBlock";var Ms=class extends Lt{constructor({value:t=cn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Jn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,le;e.push(o)}return fl(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new 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 t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ms.NAME="ObjectIdentifierValueBlock";var Ph,an=class extends At{constructor(t={}){super(t,Ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ph=an;T.ObjectIdentifier=Ph;an.NAME="OBJECT IDENTIFIER";var Qn=class extends De(Te){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=tr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",le;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=q.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Qn.NAME="relativeSidBlock";var Us=class extends Lt{constructor({value:t=cn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Qn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,le;n.push(s)}return fl(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new Qn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Us.NAME="RelativeObjectIdentifierValueBlock";var Dh,Os=class extends At{constructor(t={}){super(t,Us),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Dh=Os;T.RelativeObjectIdentifier=Dh;Os.NAME="RelativeObjectIdentifier";var Rh,Le=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Rh=Le;T.Sequence=Rh;Le.NAME="SEQUENCE";var Mh,Fs=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Mh=Fs;T.Set=Mh;Fs.NAME="SET";var Vs=class extends De(Lt){constructor({...t}={}){super(t),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 Ft=class extends _s{constructor({...t}={}){super(t,Hs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ft.NAME="SIMPLE STRING";var Ks=class extends Ft{fromBuffer(t){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=q.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ks.NAME="Utf8StringValueBlock";var Uh,Ne=class extends Ks{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Uh=Ne;T.Utf8String=Uh;Ne.NAME="UTF8String";var qs=class extends Ft{fromBuffer(t){this.valueBlock.value=q.Convert.ToUtf16String(t),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(t))}};qs.NAME="BmpStringValueBlock";var Oh,$s=class extends qs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Oh=$s;T.BmpString=Oh;$s.NAME="BMPString";var zs=class extends Ft{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=tr(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};zs.NAME="UniversalStringValueBlock";var Fh,Gs=class extends zs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Fh=Gs;T.UniversalString=Fh;Gs.NAME="UniversalString";var Vh,Ws=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Vh=Ws;T.NumericString=Vh;Ws.NAME="NumericString";var Hh,js=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Hh=js;T.PrintableString=Hh;js.NAME="PrintableString";var Kh,Zs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Kh=Zs;T.TeletexString=Kh;Zs.NAME="TeletexString";var qh,Xs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};qh=Xs;T.VideotexString=qh;Xs.NAME="VideotexString";var $h,Ys=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};$h=Ys;T.IA5String=$h;Ys.NAME="IA5String";var zh,Js=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};zh=Js;T.GraphicString=zh;Js.NAME="GraphicString";var Gh,to=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gh=to;T.VisibleString=Gh;to.NAME="VisibleString";var Wh,Qs=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Wh=Qs;T.GeneralString=Wh;Qs.NAME="GeneralString";var jh,ti=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};jh=ti;T.CharacterString=jh;ti.NAME="CharacterString";var Zh,eo=class extends to{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=zt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=zt(this.month,2),e[2]=zt(this.day,2),e[3]=zt(this.hour,2),e[4]=zt(this.minute,2),e[5]=zt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Zh=eo;T.UTCTime=Zh;eo.NAME="UTCTime";var Xh,ei=class extends eo{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let l=new Number(t[t.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(zt(this.year,4)),e.push(zt(this.month,2)),e.push(zt(this.day,2)),e.push(zt(this.hour,2)),e.push(zt(this.minute,2)),e.push(zt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(zt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Xh=ei;T.GeneralizedTime=Xh;ei.NAME="GeneralizedTime";var Yh,ri=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Yh=ri;T.DATE=Yh;ri.NAME="DATE";var Jh,ni=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Jh=ni;T.TimeOfDay=Jh;ni.NAME="TimeOfDay";var Qh,oi=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Qh=oi;T.DateTime=Qh;oi.NAME="DateTime";var td,si=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};td=si;T.Duration=td;si.NAME="Duration";var ed,ii=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ed=ii;T.TIME=ed;ii.NAME="TIME";function et(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.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(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},no=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ci=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var rd={get(r=globalThis){let t=r.crypto;if(t?.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 t}};var rr=rd;async function nd(r){let t=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"]),e=await my(t);return{privateKey:e[0],publicKey:e[1]}}async function od(r,t){let e=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"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function sd(r,t,e){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,t,e instanceof Uint8Array?e:e.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(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return mt.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return sd(this._key,e,t)}},so=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=oo.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return od(this._key,t)}};var li=8192,ml=18;function id(r){let{result:t}=dl(r),e=t.valueBlock.value;return{n:ge(e[1]),e:ge(e[2]),d:ge(e[3]),p:ge(e[4]),q:ge(e[5]),dp:ge(e[6]),dq:ge(e[7]),qi:ge(e[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 e=new Le({value:[new St({value:0}),St.fromBigInt(ye(P(r.n,"base64url"))),St.fromBigInt(ye(P(r.e,"base64url"))),St.fromBigInt(ye(P(r.d,"base64url"))),St.fromBigInt(ye(P(r.p,"base64url"))),St.fromBigInt(ye(P(r.q,"base64url"))),St.fromBigInt(ye(P(r.dp,"base64url"))),St.fromBigInt(ye(P(r.dq,"base64url"))),St.fromBigInt(ye(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ad(r){let{result:t}=dl(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ge(e[0]),e:ge(e[1])}}function gl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");let e=new Le({value:[new Le({value:[new an({value:"1.2.840.113549.1.1.1"}),new on]}),new sn({valueHex:new Le({value:[St.fromBigInt(ye(P(r.n,"base64url"))),St.fromBigInt(ye(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ge(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return et(t,"base64url")}function ye(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function cd(r){let t=id(r);return ld(t)}function yl(r){let t=ad(r);if(pl(t)>li)throw new Hr("Key size is too large");let e=ws(pe.encode({Type:yt.RSA,Data:r})),n=ee(ml,e);return new un(t,n)}function ld(r){if(pl(r)>li)throw new R("Key size is too large");let t=ud(r),e=ws(pe.encode({Type:yt.RSA,Data:gl(t.publicKey)})),n=ee(ml,e);return new so(t.privateKey,new un(t.publicKey,n))}async function wl(r){if(r>li)throw new R("Key size is too large");let t=await nd(r),e=ws(pe.encode({Type:yt.RSA,Data:gl(t.publicKey)})),n=ee(ml,e);return new so(t.privateKey,new un(t.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:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)or[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=or[l-15],h=or[l-2],p=ne(d,7)^ne(d,18)^d>>>3,m=ne(h,17)^ne(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=ne(a,6)^ne(a,11)^ne(a,25),h=f+d+If(a,c,u)+yy[l]+or[l]|0,m=(ne(n,2)^ne(n,13)^ne(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(t,e){super(),this.finished=!1,this.destroyed=!1,_f(t);let n=On(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Yr(this),this.iHash.update(t),this}digestInto(t){Yr(this),Xr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xl=(r,t,e)=>new ui(r,t).update(e).digest();xl.create=(r,t)=>new ui(r,t);function hd(r){r.lowS!==void 0&&oe("lowS",r.lowS),r.prehash!==void 0&&oe("prehash",r.prehash)}function wy(r){let t=Hn(r);he(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:by,hexToBytes:xy}=es,Re={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Re;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=pr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?pr(o.length/2|128):"";return pr(r)+s+o+t},decode(r,t){let{Err:e}=Re,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Re;if(r<Me)throw new t("integer: negative integers are not allowed");let e=pr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Re;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return by(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Re,o=typeof r=="string"?xy(r):r;tn(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=Re,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Me=BigInt(0),vt=BigInt(1),lE=BigInt(2),dd=BigInt(3),uE=BigInt(4);function vy(r){let t=wy(r),{Fp:e}=t,n=Xe(t.n,t.nBitLength),o=t.toBytes||((m,g,w)=>{let b=g.toAffine();return Ie(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let g=m.subarray(1),w=e.fromBytes(g.subarray(0,e.BYTES)),b=e.fromBytes(g.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(m){let{a:g,b:w}=t,b=e.sqr(m),y=e.mul(b,m);return e.add(e.add(y,e.mul(m,g)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Fn(m,vt,t.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:b,n:y}=t;if(g&&typeof m!="bigint"){if(We(m)&&(m=Be(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:Ce(at("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)),qt("private key",x,vt,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(e.eql(y,e.ONE))return{x:w,y:b};let x=m.is0();g==null&&(g=x?e.ONE:e.inv(y));let A=e.mul(w,g),_=e.mul(b,g),v=e.mul(y,g);if(x)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=yr(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=m.toAffine();if(!e.isValid(g)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),y=i(g);if(!e.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||!e.isValid(g))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:w,y:b}=g||{};if(!g||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let y=x=>e.eql(x,e.ZERO);return y(w)&&y(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let w=e.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(at("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(e.isOdd)return!e.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=e.eql(e.mul(w,_),e.mul(x,y)),B=e.eql(e.mul(b,_),e.mul(A,y));return v&&B}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:g,b:w}=t,b=e.mul(w,dd),{px:y,py:x,pz:A}=this,_=e.ZERO,v=e.ZERO,B=e.ZERO,k=e.mul(y,y),Y=e.mul(x,x),H=e.mul(A,A),V=e.mul(y,x);return V=e.add(V,V),B=e.mul(y,A),B=e.add(B,B),_=e.mul(g,B),v=e.mul(b,H),v=e.add(_,v),_=e.sub(Y,v),v=e.add(Y,v),v=e.mul(_,v),_=e.mul(V,_),B=e.mul(b,B),H=e.mul(g,H),V=e.sub(k,H),V=e.mul(g,V),V=e.add(V,B),B=e.add(k,k),k=e.add(B,k),k=e.add(k,H),k=e.mul(k,V),v=e.add(v,k),H=e.mul(x,A),H=e.add(H,H),k=e.mul(H,V),_=e.sub(_,k),B=e.mul(H,Y),B=e.add(B,B),B=e.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=e.ZERO,B=e.ZERO,k=e.ZERO,Y=t.a,H=e.mul(t.b,dd),V=e.mul(w,x),D=e.mul(b,A),I=e.mul(y,_),N=e.add(w,b),S=e.add(x,A);N=e.mul(N,S),S=e.add(V,D),N=e.sub(N,S),S=e.add(w,y);let E=e.add(x,_);return S=e.mul(S,E),E=e.add(V,I),S=e.sub(S,E),E=e.add(b,y),v=e.add(A,_),E=e.mul(E,v),v=e.add(D,I),E=e.sub(E,v),k=e.mul(Y,S),v=e.mul(H,I),k=e.add(v,k),v=e.sub(D,k),k=e.add(D,k),B=e.mul(v,k),D=e.add(V,V),D=e.add(D,V),I=e.mul(Y,I),S=e.mul(H,S),D=e.add(D,I),I=e.sub(V,I),I=e.mul(Y,I),S=e.add(S,I),V=e.mul(D,S),B=e.add(B,V),V=e.mul(E,S),v=e.mul(N,v),v=e.sub(v,V),V=e.mul(N,D),k=e.mul(E,k),k=e.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}=t;qt("scalar",g,Me,b);let y=d.ZERO;if(g===Me)return y;if(this.is0()||g===vt)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>Me||v>Me;)A&vt&&(B=B.add(Y)),v&vt&&(k=k.add(Y)),Y=Y.double(),A>>=vt,v>>=vt;return x&&(B=B.negate()),_&&(k=k.negate()),k=new d(e.mul(k.px,w.beta),k.py,k.pz),B.add(k)}multiply(g){let{endo:w,n:b}=t;qt("scalar",g,vt,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(e.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===Me||v===vt||!_.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}=t;if(g===vt)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}=t;return g===vt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(g=!0){return oe("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return oe("isCompressed",g),Be(this.toRawBytes(g))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,p=os(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Ey(r){let t=Hn(r);return he(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function pd(r){let t=Ey(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.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({...t,toBytes(I,N,S){let E=N.toAffine(),C=e.toBytes(E.x),L=Ie;return oe("isCompressed",S),S?L(Uint8Array.from([N.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,e.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=Ce(E);if(!Fn(C,vt,e.ORDER))throw new Error("Point is not on curve");let L=f(C),M;try{M=e.sqrt(L)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let U=(M&vt)===vt;return(S&1)===1!==U&&(M=e.neg(M)),{x:C,y:M}}else if(N===s&&S===4){let C=e.fromBytes(E.subarray(0,e.BYTES)),L=e.fromBytes(E.subarray(e.BYTES,2*e.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=>Be(Ze(I,t.nByteLength));function h(I){let N=n>>vt;return I>N}function p(I){return h(I)?i(-I):I}let m=(I,N,S)=>Ce(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=t.nByteLength;return N=at("compactSignature",N,S*2),new g(m(N,0,S),m(N,S,2*S))}static fromDER(N){let{r:S,s:E}=Re.toSig(at("DER",N));return new g(S,E)}assertValidity(){qt("r",this.r,vt,n),qt("s",this.s,vt,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:S,s:E,recovery:C}=this,L=_(at("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let M=C===2||C===3?S+t.n:S;if(M>=e.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*$),nt=c.BASE.multiplyAndAddUnsafe(K,O,J);if(!nt)throw new Error("point at infinify");return nt.assertValidity(),nt}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 Re.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(t.n);return Of(t.randomBytes(I),t.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=We(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=t.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let N=Ce(I),S=I.length*8-t.nBitLength;return S>0?N>>BigInt(S):N},_=t.bits2int_modN||function(I){return i(A(I))},v=Vn(t.nBitLength);function B(I){return qt("num < 2^"+t.nBitLength,I,Me,v),Ze(I,t.nByteLength)}function k(I,N,S=Y){if(["recovered","canonical"].some(xt=>xt in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:C}=t,{lowS:L,prehash:M,extraEntropy:U}=S;L==null&&(L=!0),I=at("msgHash",I),hd(S),M&&(I=at("prehashed msgHash",E(I)));let K=_(I),$=u(N),O=[B($),B(K)];if(U!=null&&U!==!1){let xt=U===!0?C(e.BYTES):U;O.push(at("extraEntropy",xt))}let J=Ie(...O),nt=K;function bt(xt){let Et=A(xt);if(!l(Et))return;let Bt=a(Et),Kt=c.BASE.multiply(Et).toAffine(),Dt=i(Kt.x);if(Dt===Me)return;let fe=i(Bt*i(nt+Dt*$));if(fe===Me)return;let be=(Kt.x===Dt?0:2)|Number(Kt.y&vt),Tn=fe;return L&&h(fe)&&(Tn=p(fe),be^=1),new g(Dt,Tn,be)}return{seed:J,k2sig:bt}}let Y={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function V(I,N,S=Y){let{seed:E,k2sig:C}=k(I,N,S),L=t;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=at("msgHash",N),S=at("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"||We(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(be){if(!(be instanceof Re.Err))throw be}!O&&U!=="der"&&(O=g.fromCompact(C))}J=c.fromHex(S)}catch{return!1}if(!O||L&&O.hasHighS())return!1;M&&(N=t.hash(N));let{r:nt,s:bt}=O,xt=_(N),Et=a(bt),Bt=i(xt*Et),Kt=i(nt*Et),Dt=c.BASE.multiplyAndAddUnsafe(J,Bt,Kt)?.toAffine();return Dt?i(Dt.x)===nt:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:x,sign:V,verify:D,ProjectivePoint:c,Signature:g,utils:w}}function Ay(r){return{hash:r,hmac:(t,...e)=>xl(r,t,ac(...e)),randomBytes:Yo}}function md(r,t){let e=n=>pd({...r,...Ay(n)});return Object.freeze({...e(t),create:e})}var wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),gd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Sy=BigInt(1),vl=BigInt(2),yd=(r,t)=>(r+t/vl)/t;function _y(r){let t=wd,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=it(f,e,t)*f%t,d=it(l,e,t)*f%t,h=it(d,vl,t)*u%t,p=it(h,o,t)*h%t,m=it(p,s,t)*p%t,g=it(m,a,t)*m%t,w=it(g,c,t)*g%t,b=it(w,a,t)*m%t,y=it(b,e,t)*f%t,x=it(y,i,t)*p%t,A=it(x,n,t)*u%t,_=it(A,vl,t);if(!El.eql(El.sqr(_),r))throw new Error("Cannot find square root");return _}var El=Xe(wd,void 0,void 0,{sqrt:_y}),Yt=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 t=gd,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Sy*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=yd(s*r,t),c=yd(-n*r,t),u=Q(r-a*e-c*o,t),f=Q(-a*n-c*s,t),l=u>i,d=f>i;if(l&&(u=t-u),d&&(f=t-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},fd),bE=BigInt(0);var xE=Yt.ProjectivePoint;function Vt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Ct(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Al(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function bd(r,t){let e=en.digest(t instanceof Uint8Array?t:t.subarray());if(Al(e))return e.then(({digest:n})=>Yt.sign(n,r).toDERRawBytes()).catch(n=>{throw new ro(String(n))});try{return Yt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new ro(String(n))}}function xd(r,t,e){let n=en.digest(e instanceof Uint8Array?e:e.subarray());if(Al(n))return n.then(({digest:o})=>Yt.verify(t,o,r)).catch(o=>{throw new no(String(o))});try{return Yt.verify(t,n.digest,r)}catch(o){throw new no(String(o))}}var io=class{type="secp256k1";raw;_key;constructor(t){this._key=Ad(t),this.raw=vd(this._key)}toMultihash(){return Se.digest(de(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}verify(t,e){return xd(this._key,e,t)}},fi=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Ed(t),this.publicKey=new io(e??Sd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ut(this.raw,t.raw)}sign(t){return bd(this.raw,t)}};function Sl(r){return new io(r)}async function _d(){let r=By();return new fi(r)}function vd(r){return Yt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ed(r){try{return Yt.getPublicKey(r,!0),r}catch(t){throw new Ln(String(t))}}function Ad(r){try{return Yt.ProjectivePoint.fromHex(r),r}catch(t){throw new Hr(String(t))}}function Sd(r){try{return Yt.getPublicKey(r,!0)}catch(t){throw new Ln(String(t))}}function By(){return Yt.utils.randomPrivateKey()}async function Bd(r,t){if(r==="Ed25519")return Zf();if(r==="secp256k1")return _d();if(r==="RSA")return wl(t??2048);throw new qe}function fn(r){let{Type:t,Data:e}=pe.decode(r),n=e??new Uint8Array;switch(t){case yt.RSA:return yl(n);case yt.Ed25519:return _c(n);case yt.secp256k1:return Sl(n);default:throw new qe}}function Cd(r){let{Type:t,Data:e}=pe.decode(r.digest),n=e??new Uint8Array;switch(t){case yt.Ed25519:return _c(n);case yt.secp256k1:return Sl(n);default:throw new qe}}function de(r){return pe.encode({Type:yt[r.type],Data:r.raw})}var Id=Symbol.for("nodejs.util.inspect.custom"),Cy=114,ao=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Uo]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return mt.createV1(Cy,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ut(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ut(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Id](){return`PeerId(${this.toString()})`}},co=class extends ao{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},lo=class extends ao{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},uo=class extends ao{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Iy=2336,fo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Se.digest(P(this.url))}[Id](){return`PeerId(${this.url})`}[Uo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return mt.createV1(Iy,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=et(t)),t.toString()===this.toString())}};var ky=114,kd=2336;function we(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=re(Z.decode(`z${r}`));else{if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=re(t.decode(r))}return hn(e)}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 qe}function Td(r){return _l(r.publicKey)}function hn(r){if(Ly(r))return new co({multihash:r});if(Ty(r))try{let t=Cd(r);if(t.type==="Ed25519")return new lo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new uo({multihash:r,publicKey:t})}catch{let e=et(r.digest);return new fo(new URL(e))}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 t=et(r.multihash.digest);return new fo(new URL(t))}return hn(r.multihash)}function Ty(r){return r.code===Se.code}function Ly(r){return r.code===en.code}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Cl=hr(Nd(),1);var po=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Il=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Pd=r=>globalThis.DOMException===void 0?new Il(r):new DOMException(r),Dd=r=>{let t=r.reason===void 0?Pd("This operation was aborted."):r.reason;return t instanceof Error?t:Pd(t)};function mo(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Dd(d));let h=()=>{f(Dd(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(e===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 ${e} milliseconds`,f(l))},e),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function kl(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var go=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=kl(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var sr=class extends Cl.default{#t;#e;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:go,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#b(){return this.#e||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#n===void 0){let e=this.#p-t;if(e<0)this.#s=this.#t?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},e)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#A;if(this.#b&&this.#x){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#t?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#h()}async#S(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=mo(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#S(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof po&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#o}get isPaused(){return this.#i}};function pi(r){let t=[Zt.A];return r==null?t:Array.isArray(r)?r.length===0?t: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(t=>({name:t.name,type:Zt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Zt[t.type],TTL:t.TTL??t.ttl??Tl,data:t.data instanceof Uint8Array?et(t.data):t.data}))}}var Dy=4;function Ll(r,t={}){let e=new sr({concurrency:t.queryConcurrency??Dy});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(o.types).forEach(a=>{s.append("type",Zt[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=mi(await a.json());return o.onProgress?.(new dt("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(t){this.lru=(0,Od.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return mi({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Zt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Tl)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Fd(r){return new Nl(r)}var Ry=1e3,gi=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Fd(t.cacheSize??Ry),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Rd())}async query(t,e={}){let n=pi(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let f of u.Answer)this.cache.add(t,f);return u}catch(u){a.push(u),e.onProgress?.(new dt("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Zt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Zt||(Zt={}));function Vd(r={}){return new gi(r)}var yi=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var 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 cS=parseInt("0xFFFF",16),lS=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 t=0;if(r=r.toString().trim(),$d(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Hy(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=$d(e[n]),i;s&&(i=Rl(e[n]),e[n]=et(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,et(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},zd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var 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 t=$y(...r);Ml[t.code]=t,mn[t.name]=t});function $y(r,t,e,n,o){return{code:r,size:t,name:e,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 GS=W("ip4"),WS=W("ip6"),jS=W("ipcidr");function Vl(r,t){switch(W(r).code){case 4:case 41:return Gy(t);case 42:return Fl(t);case 6:case 273:case 33:case 132:return jd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fl(t);case 421:return Xy(t);case 444:return Wd(t);case 445:return Wd(t);case 466:return Zy(t);case 481:return globalThis.encodeURIComponent(Fl(t));default:return et(t,"base16")}}function Hl(r,t){switch(W(r).code){case 4:return Gd(t);case 41:return Gd(t);case 42:return Ol(t);case 6:case 273:case 33:case 132:return Kl(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ol(t);case 421:return Wy(t);case 444:return Yy(t);case 445:return Jy(t);case 466:return jy(t);case 481:return Ol(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}var Ul=Object.values($n).map(r=>r.decoder),zy=function(){let r=Ul[0].or(Ul[1]);return Ul.slice(2).forEach(t=>r=r.or(t)),r}();function Gd(r){if(!bi(r))throw new Error("invalid ip address");return Rl(r)}function Gy(r){let t=zd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!bi(t))throw new Error("invalid ip address");return t}function Kl(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function jd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ol(r){let t=P(r),e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function Fl(r){let t=ie(r);if(r=r.slice(pt(t)),r.length!==t)throw new Error("inconsistent lengths");return et(r)}function Wy(r){let t;r[0]==="Q"||r[0]==="1"?t=re(Z.decode(`z${r}`)).bytes:t=mt.parse(r).multihash.bytes;let e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function jy(r){let t=zy.decode(r),e=Uint8Array.from(kt(t.length));return Vt([e,t],e.length+t.length)}function Zy(r){let t=ie(r),e=r.slice(pt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+et(e,"base64url")}function Xy(r){let t=ie(r),e=r.slice(pt(t));if(e.length!==t)throw new Error("inconsistent lengths");return et(e,"base58btc")}function Yy(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Wt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Kl(n);return Vt([e,o],e.length+o.length)}function Jy(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Wt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Kl(n);return Vt([e,o],e.length+o.length)}function Wd(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=et(t,"base32"),o=jd(e);return`${n}:${o}`}function Zd(r){r=ql(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Yd("invalid address: "+r);if(a.path===!0){n=ql(o.slice(s).join("/")),t.push([a.code,Hl(a.code,n)]),e.push([a.code,n]);break}let c=Hl(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Vl(a.code,c)])}return{string:Xd(e),bytes:zl(t),tuples:t,stringTuples:e,path:n}}function $l(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ie(r,o),i=pt(s),a=W(s),c=Qy(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Yd("Invalid address Uint8Array: "+et(r,"base16"));t.push([s,u]);let f=Vl(s,u);if(e.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Xd(e),tuples:t,stringTuples:e,path:n}}function Xd(r){let t=[];return r.map(e=>{let n=W(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ql(t.join("/"))}function zl(r){return Vt(r.map(t=>{let e=W(t[0]),n=Uint8Array.from(kt(e.code));return t.length>1&&t[1]!=null&&(n=Vt([n,t[1]])),n}))}function Qy(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ie(t instanceof Uint8Array?t:Uint8Array.from(t));return e+pt(e)}}function ql(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Yd(r){return new Error("Error parsing address: "+r)}var tw=Symbol.for("nodejs.util.inspect.custom"),Wl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),ew=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Gl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},xi=class r{bytes;#t;#e;#s;#a;[Wl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=$l(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Zd(t)}else if(ar(t))e=$l(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#s=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=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??""}`),ew.includes(h)&&(e=i.name,o=443,n=`${p??""}${s}`,t=h===f.code?6:4),(h===i.code||h===a.code)&&(e=W(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(e=W(h).name,n=`${p??""}${s}`,t=h===u.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},W(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>W(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#s.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(zl(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===mn.p2p.code&&t.push([n,o]),n===mn["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?et(Z.decode(`z${n}`),"base58btc"):et(mt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=gn.get(e.name);if(n==null)throw new Gl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>rt(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[tw](){return`Multiaddr(${this.#t})`}};var gn=new Map;function ar(r){return!!r?.[Wl]}function rt(r){return new xi(r)}var rw=32,{code:nw}=W("dnsaddr"),jl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},_r=async function(t,e={}){let n=e.maxRecursiveDepth??rw;if(n===0)throw new jl("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===nw)??[],i=await(e?.dns??Vd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Zt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=rt(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var ip=hr(sp(),1),Ai=ip.default;var lw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:_r}},transportManager:{faultTolerance:He.FATAL_ALL}};async function ap(r){let t=Ai(lw,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return t}function uw(r,t){try{if(typeof r=="string"&&r.length>0)return fw(r);if(typeof r=="number"&&isFinite(r))return t?.long?dw(r):hw(r);throw new Error("Value is not a string or number.")}catch(e){let n=pw(e)?`${e.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 t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var _i=uw;function hw(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function dw(r){let t=Math.abs(r);return t>=864e5?Si(r,t,864e5,"day"):t>=36e5?Si(r,t,36e5,"hour"):t>=6e4?Si(r,t,6e4,"minute"):t>=1e3?Si(r,t,1e3,"second"):`${r} ms`}function Si(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function pw(r){return typeof r=="object"&&r!==null&&"message"in r}function Xl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=_i,e.destroy=u,Object.keys(r).forEach(f=>{e[f]=r[f]}),e.names=[],e.skips=[],e.formatters={};function t(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return e.colors[Math.abs(l)%e.colors.length]}e.selectColor=t;function e(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let w=m,b=Number(new Date),y=b-(l||b);w.diff=y,w.prev=l,w.curr=b,l=b,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=e.formatters[v];if(typeof B=="function"){let k=g[x];_=B.call(w,k),g.splice(x,1),x--}return _}),e.formatArgs.call(w,g),(w.log||e.log).apply(w,g)}return m.namespace=f,m.useColors=e.useColors(),m.color=e.selectColor(f),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(f)),p),set:g=>{d=g}}),typeof e.init=="function"&&e.init(m),m}function n(f,l){let d=e(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){e.save(f),e.namespaces=f,e.names=[],e.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?e.skips.push(new RegExp("^"+f.substr(1)+"$")):e.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...e.names.map(a),...e.skips.map(a).map(l=>"-"+l)].join(",");return e.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=e.skips.length;l<d;l++)if(e.skips[l].test(f))return!1;for(l=0,d=e.names.length;l<d;l++)if(e.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var 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 t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var 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(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var cp=Xl({formatArgs:yw,save:bw,load:xw,useColors:gw,setupFormatters:Ew,colors:mw,storage:Bi,log:ww});var Gt=cp;Gt.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);Gt.formatters.t=r=>r==null?"undefined":Wt.baseEncode(r);Gt.formatters.m=r=>r==null?"undefined":Hc.baseEncode(r);Gt.formatters.p=r=>r==null?"undefined":r.toString();Gt.formatters.c=r=>r==null?"undefined":r.toString();Gt.formatters.k=r=>r==null?"undefined":r.toString();Gt.formatters.a=r=>r==null?"undefined":r.toString();Gt.formatters.e=r=>r==null?"undefined":lp(r.stack)??lp(r.message)??r.toString();function Aw(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ci(){return{forComponent(r){return Sw(r)}}}function Sw(r){let t=Aw(`${r}:trace`);return Gt.enabled(`${r}:trace`)&&Gt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Gt(`${r}:trace`)),Object.assign(Gt(r),{error:Gt(`${r}:error`),trace:t})}function lp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Br(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function Ii(r){let t=re(Z.decode(`z${r}`));return hn(t)}var Ue=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Br(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Br(this.map.values(),t=>t.key)}values(){return Br(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Cr=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return Br(this.set.entries(),t=>{let e=Ii(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Ii(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Br(this.set.values(),t=>Ii(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var pp=Symbol.for("@achingbrain/uint8arraylist");function dp(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Ti(r){return!!r?.[pp]}var wt=class r{bufs;length;[pp]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ti(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ti(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=dp(this.bufs,t);return e.buf[e.index]}set(t,e){let n=dp(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ti(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Vt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Vt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ti(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Ct(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Ct(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Yl=64,ue=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Yl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ft(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ut(this.fp,t.fp):!1}};function Ir(r,t){return Math.floor(Math.random()*(t-r))+r}var kr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");let e=Ir(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ue))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=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,t){let e=Jl[t],n=mp[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Bw(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Jl[t],o=mp[t],s=r;for(;s.length>0;){let i=gp.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Ql(r,{size:t=32,utf8Buffer:e}={}){if(!Jl[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Bw(r,t,e);r=gp.encode(r)}return _w(r,t)}var Cw=hr(hp(),1);var wo={hash:r=>Number(Ql(r,{size:32})),hashV:(r,t)=>Iw(wo.hash(r,t))};function Iw(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var kw=500,bo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??wo,this.seed=t.seed??Ir(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new kr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new kr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))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(e);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(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=P(t));let e=new ue(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},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,t=.001){let e=Lw(t),n=Tw[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Yl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Li=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??wo,this.seed=t.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(t){if(typeof t=="string"&&(t=P(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new bo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function tu(r,t=.001,e){return new Li({...yp(r,t),...e??{}})}var xo;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ft(0),payloadType:ft(0),payload:ft(0),signature:ft(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(xo||(xo={}));var Ni=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var bn=class r{static createFromProtobuf=async t=>{let e=xo.decode(t),n=fn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=wp(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Ni("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=xo.encode({publicKey:de(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ut(this.marshal(),t.marshal())}async validate(t){let e=wp(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},wp=(r,t,e)=>{let n=P(r),o=kt(n.byteLength),s=kt(t.length),i=kt(e.length);return new wt(o,n,s,t,i,e)};function bp(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var xp="libp2p-peer-record",vp=Uint8Array.from([3,1]);var vo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Ot((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:ft(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=>Ut(s,n.codec()),n.decode=(s,i)=>Mt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Ot((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:ft(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})),e),r.encode=n=>Ut(n,r.codec()),r.decode=(n,o)=>Mt(n,r.codec(),o)})(vo||(vo={}));var Tr=class r{static createFromProtobuf=t=>{let e=vo.decode(t),n=hn(re(e.peerId)),o=(e.addresses??[]).map(i=>rt(i.multiaddr)),s=e.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(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=vo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!bp(this.multiaddrs,t.multiaddrs))}};function Nw(r){return r[Symbol.asyncIterator]!=null}function Pw(r){if(Nw(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var Eo=Pw;var cr={},xn=r=>{r.addEventListener("message",t=>{xn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{xn.dispatchEvent("message",r,t)})};xn.addEventListener=(r,t)=>{cr[r]==null&&(cr[r]=[]),cr[r].push(t)};xn.removeEventListener=(r,t)=>{cr[r]!=null&&(cr[r]=cr[r].filter(e=>e===t))};xn.dispatchEvent=function(r,t,e){cr[r]!=null&&cr[r].forEach(n=>n(t,e))};var eu=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,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f?.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,t,e,n)=>async()=>{let o=Ep();return globalThis.postMessage({type:t,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===e&&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 e=new EventTarget;return eu.addEventListener("message",Ap(e,"requestReadLock",ru,nu,ou)),eu.addEventListener("message",Ap(e,"requestWriteLock",su,iu,au)),e}return{isWorker:!0,readLock:e=>Sp(e,ru,ou,nu),writeLock:e=>Sp(e,su,au,iu)}};var Lr={},lr;async function cu(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var Rw=(r,t)=>{if(lr.isWorker===!0)return{readLock:lr.readLock(r,t),writeLock:lr.writeLock(r,t)};let e=new sr({concurrency:1}),n;return{async readLock(){if(n!=null)return cu(n,t);n=new sr({concurrency:t.concurrency,autoStart:!1});let o=n,s=cu(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,cu(e,t)}}},Mw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function lu(r){let t=Object.assign({},Mw,r);return lr==null&&(lr=_p(t),lr.isWorker!==!0&&(lr.addEventListener("requestReadLock",e=>{Lr[e.data.name]!=null&&Lr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),lr.addEventListener("requestWriteLock",async e=>{Lr[e.data.name]!=null&&Lr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Lr[t.name]==null&&(Lr[t.name]=Rw(t.name,t)),Lr[t.name]}var vn;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ot((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:ft(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=>Ut(i,o.codec()),o.decode=(i,a)=>Mt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ot((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=>Ut(i,o.codec()),o.decode=(i,a)=>Mt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ot((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=>Ut(o,r.codec()),r.decode=(o,s)=>Mt(o,r.codec(),s)})(vn||(vn={}));var Pi;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ft(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(Pi||(Pi={}));var Di;(function(r){let t;r.codec=()=>(t==null&&(t=Ot((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ut(e,r.codec()),r.decode=(e,n)=>Mt(e,r.codec(),n)})(Di||(Di={}));function En(r,t){let e=vn.decode(t);if(e.publicKey!=null&&r.publicKey==null){let s=fn(e.publicKey);r=_l(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:r,addresses:e.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:rt(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}var Oe="/",Bp=new TextEncoder().encode(Oe),Ri=Bp[0],Nr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ri)throw new Error("Invalid key")}toString(t="utf8"){return et(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Oe))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Bp),this._buf[0]!==Ri){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ri,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ri;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Oe).slice(1)}type(){return Uw(this.baseNamespace())}name(){return Ow(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Oe)||(t+=Oe),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Oe):new r(t.slice(0,-1).join(Oe))}child(t){return this.toString()===Oe?t:t.toString()===Oe?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Fw(t.map(e=>e.namespaces()))])}};function Uw(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Ow(r){let t=r.split(":");return t[t.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 t=r.toCID().toString();return new Nr(`${uu}${t}`)}async function Cp(r,t,e){let n=new Map;for(let o of e){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=rt(o.multiaddr)),!ar(o.multiaddr))throw new R("Multiaddr was invalid");if(!await t(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Ui(r,t,e,n){if(t==null)throw new R("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.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(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Mi(d,{validate:Ip})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Mi(d,{validate:kp,map:Tp})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Mi([...a.entries()],{validate:Ip})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Mi([...h.entries()],{validate:kp,map:Tp})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=de(o.id.publicKey):t.publicKey!=null?f=de(t.publicKey):r.publicKey!=null&&(f=de(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,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function Ip(r,t){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function kp(r,t){if(typeof r!="string")throw new R("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new R("Tag value must be an integer");if(t.value<0||t.value>100)throw new R("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new R("Tag ttl must be an integer");if(t.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Tp(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Oi(r,t){let e=r.toString().split("/")[2],n=mt.parse(e,Wt),o=hi(n);return En(o,t)}function Vw(r){return r==null?{}:{prefix:uu,filters:(r.filters??[]).map(t=>({key:e,value:n})=>t(Oi(e,n))),orders:(r.orders??[]).map(t=>(e,n)=>t(Oi(e.key,e.value),Oi(n.key,n.value)))}}var Fi=class{peerId;datastore;lock;addressFilter;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=lu({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(An(t))}async delete(t){if(this.peerId.equals(t))throw new R("Cannot delete self peer");await this.datastore.delete(An(t))}async load(t){let e=await this.datastore.get(An(t));return En(t,e)}async save(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,s,n,o)}async patch(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async merge(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ui(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Vw(t??{}))){let o=Oi(e,n);o.id.equals(this.peerId)||(yield o)}}async#t(t){try{let e=await this.datastore.get(An(t)),n=En(t,e);return{existingBuf:e,existingPeer:n}}catch(e){e.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",e)}return{}}async#e(t,e,n,o){let s=vn.encode(e);return n!=null&&ut(s,n)?{peer:En(t,s),previous:o,updated:!1}:(await this.datastore.put(An(t),s),{peer:En(t,s),previous:o,updated:!0})}};var fu=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Fi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Eo(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await bn.openAndCertify(t,Tr.DOMAIN),o=hi(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=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:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function Lp(r,t={}){return new fu(r,t)}var Vi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function Hw(r){return r[Symbol.asyncIterator]!=null}function Kw(r){if(Hw(r))return(async()=>{for await(let t of r);})();for(let t of r);}var hu=Kw;function qw(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Np=qw;function $w(r){return r[Symbol.asyncIterator]!=null}function zw(r,t){let e=0;if($w(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Np(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var Pr=zw;function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r,t){return Gw(r)?async function*(){yield*(await Eo(r)).sort(t)}():function*(){yield*Eo(r).sort(t)}()}var du=Ww;function jw(r){return r[Symbol.asyncIterator]!=null}function Zw(r,t){return jw(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var pu=Zw;var Hi=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await hu(this.putMany(t,n)),t=[],await hu(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>du(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=Pr(n,()=>o++>=s)}return t.limit!=null&&(n=pu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>du(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=Pr(n,()=>s++>=o)}return t.limit!=null&&(n=pu(n,t.limit)),n}};var Ki=class extends Hi{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new Vi;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new Nr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new Nr(t)}};function Pp(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Xw=r=>r;function mu(r,t){let e=r.getPeerId();return e!=null&&we(e).equals(t)&&(r=r.decapsulate(rt(`/p2p/${t.toString()}`))),r}var qi=4,$i=41,Yw=54,Jw=55,Qw=6,tb=273,zi=class{log;components;listen;announce;appendAnnounce;observed;announceFilter;ipDomainMappings;publicAddressMappings;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.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=e.announceFilter??Xw,this._updatePeerStoreAddresses=Pp(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>rt(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>rt(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>rt(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>rt(t))}addObservedAddr(t){t=mu(t,this.components.peerId);let e=t.toString();this.observed.has(e)||this.observed.set(e,{confident:!1})}confirmObservedAddr(t){t=mu(t,this.components.peerId);let e=t.toString(),o=(this.observed.get(e)??{confident:!1}).confident;this.observed.set(e,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=mu(t,this.components.peerId);let e=t.toString();this.observed.delete(e)}getAddresses(){let t=this.getAnnounceAddrs();t.length===0&&(t=this.components.transportManager.getAddrs()),t=t.concat(...this.getAppendAnnounceAddrs(),Array.from(this.observed).filter(([s,i])=>i.confident).map(([s])=>rt(s)));let e=[];t.forEach(s=>{let i=s.stringTuples(),a;if((i[0][0]===qi||i[0][0]===$i)&&i[1][0]===Qw?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}`,e.push(rt(`/${i.map(f=>[W(f[0]).name,f[1]].join("/")).join("/")}`))}),t=t.concat(e);let n=[];for(let s of t){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]=Yw,i[f][1]=u.domain,a=!0),i[f][0]===$i&&(i[f][0]=Jw,i[f][1]=u.domain,a=!0));a&&n.push(rt(`/${i.map(c=>[W(c[0]).name,c[1]].join("/")).join("/")}`))}t=t.concat(n);let o=new Set;return t=t.filter(s=>{let i=s.toString();return o.has(i)?!1:(o.add(i),!0)}),this.announceFilter(Array.from(o).map(s=>{let i=rt(s);return i.protos().pop()?.path===!0||i.getPeerId()===this.components.peerId.toString()?i:i.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}addDNSMapping(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=[...this.publicAddressMappings.entries()].some(([s,i])=>i.some(a=>a.externalIp===n));this.ipDomainMappings.set(n,{domain:t,confident:o})}),this._updatePeerStoreAddresses()}removeDNSMapping(t){for(let[e,n]of this.ipDomainMappings.entries())n.domain===t&&(this.log("remove DNS mapping for %s",t),this.ipDomainMappings.delete(e));this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${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(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${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(t="Missing service"){super(t),this.name="MissingServiceError"}},Wi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},Sn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Ao=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},ji=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Zi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},Xi=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},So=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Dr=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Yi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Ji=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},Rr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Mr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Qi=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var gu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=Ci())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Wo(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},rb=["metrics","connectionProtector","dns"],nb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Rp(r={}){let t=new gu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!nb.includes(o)){let i=t.components[o];if(i==null&&!rb.includes(o))throw new Gi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function Mp(r){let t={};for(let e of Object.values(r.components))for(let n of ob(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of sb(e))if(t[n]!==!0)throw new Wi(`Service "${ib(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function ob(r){return Array.isArray(r?.[Pn])?r[Pn]:[]}function sb(r){return Array.isArray(r?.[Xa])?r[Xa]:[]}function ib(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Op=hr(Up(),1),ab=["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"],cb=ab.map(r=>new Op.Netmask(r));function yu(r){for(let t of cb)if(t.contains(r))return!0;return!1}function lb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ub(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return yu(o)}function fb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function hb(r){let t=r.split(":"),e=t[t.length-1];return yu(e)}function db(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 ta(r){return ir(r)?yu(r):lb(r)?ub(r):fb(r)?hb(r):pn(r)?db(r):void 0}var pb=r=>r.toString().split("/").slice(1),_n=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>_n(e=>e===r).match(t),pattern:r}),Ur=()=>({match:r=>_n(t=>typeof t=="string").match(r),pattern:"{string}"}),Bo=()=>({match:r=>_n(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),tt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{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:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Pt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function ct(...r){function t(o){let s=pb(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ra=G(z("dns4"),Ur()),na=G(z("dns6"),Ur()),oa=G(z("dnsaddr"),Ur()),bu=G(z("dns"),Ur()),U6=ct(ra,j(tt())),O6=ct(na,j(tt())),F6=ct(oa,j(tt())),V6=ct(Pt(bu,oa,ra,na),j(tt())),Fp=G(z("ip4"),_n(ir)),Vp=G(z("ip6"),_n(pn)),xu=Pt(Fp,Vp),Fe=Pt(xu,bu,ra,na,oa),H6=ct(Pt(xu,G(Pt(bu,oa,ra,na),j(tt())))),K6=ct(Fp),q6=ct(Vp),$6=ct(xu),vu=G(Fe,z("tcp"),Bo()),Io=G(Fe,z("udp"),Bo()),Eu=ct(G(vu,j(tt()))),z6=ct(Io),Au=G(Io,z("quic"),j(tt())),sa=G(Io,z("quic-v1"),j(tt())),mb=Pt(Au,sa),G6=ct(Au),W6=ct(sa),wu=Pt(Fe,vu,Io,Au,sa),Hp=Pt(G(wu,z("ws"),j(tt()))),ko=ct(Hp),Kp=Pt(G(wu,z("wss"),j(tt())),G(wu,z("tls"),j(G(z("sni"),Ur())),z("ws"),j(tt()))),Su=ct(Kp),qp=G(Io,z("webrtc-direct"),j(Co()),j(Co()),j(tt())),_u=ct(qp),$p=G(sa,z("webtransport"),j(Co()),j(Co()),j(tt())),Bu=ct($p),ea=Pt(Hp,Kp,G(vu,j(tt())),G(mb,j(tt())),G(Fe,j(tt())),qp,$p,tt()),j6=ct(ea),gb=G(ea,z("p2p-circuit"),tt()),To=ct(gb),yb=Pt(G(ea,z("p2p-circuit"),z("webrtc"),j(tt())),G(ea,z("webrtc"),j(tt())),G(z("webrtc"),j(tt()))),Cu=ct(yb),wb=Pt(G(Fe,z("tcp"),Bo(),z("http"),j(tt())),G(Fe,z("http"),j(tt()))),Z6=ct(wb),bb=Pt(G(Fe,z("tcp"),Pt(G(z("443"),z("http")),G(Bo(),z("https"))),j(tt())),G(Fe,z("tls"),z("http"),j(tt())),G(Fe,z("https"),j(tt()))),X6=ct(bb),xb=Pt(G(z("memory"),Ur(),j(tt()))),Y6=ct(xb);var vb=4,Eb=41;function zp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(ko.matches(t))return!1;let e=t.stringTuples();return e[0][0]===vb||e[0][0]===Eb?!!ta(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var Gp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Ab=new WeakMap;function Sb({clearTimeout:r,setTimeout:t}={}){return(e,{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=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Ab.set(l,()=>{c(s),s=null,i()}),l}}var _b=Sb(),Wp=_b;var ia=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},aa=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ca=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new Iu}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new 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(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},Iu=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function la(r){if(Oo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:we(e),r.forEach(n=>{if(!ar(n))throw new Ke("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let s=we(o);if(t?.equals(s)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Bb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Bb;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}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(t,e={}){this.maxConnections=e.maxConnections??Yp.maxConnections,this.allow=e.allow??Yp.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new Ue;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await jp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var da=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Bn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new da(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new da(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ku=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function pa(r={}){return Cb(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Cb(r,t){t=t??{};let e=t.onEnd,n=new Bn,o,s,i,a=ht(),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=ht()})}},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(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new 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)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(g){return m.end(g),e!=null&&(e(g),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Tu=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Cn(r,t,e,n){let o=new Tu(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ma=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function ur(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ma(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ma(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ga=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ib(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ya=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Ib(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ot(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(t={}){let e=new ga(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await ur(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var In=class extends ve{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new aa;let n=new ya(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new te)}),this.clear()}async onEmpty(t){this.size!==0&&await Cn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Cn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Cn(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=pa({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var wa=class extends In{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ve(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var kb=4,Tb=41,Lb=53,Nb=54,Pb=55,Db=56;function Lu(r){try{let[[t,e]]=r.stringTuples();if(e==null)return!0;if(t===Lb||t===Nb||t===Pb||t===Db)return!1;if(t===kb||t===Tb)return ta(e)??!1}catch{}return!0}function Rb(r,t){let e=Eu.exactMatch(r.multiaddr),n=Eu.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Su.exactMatch(r.multiaddr),s=Su.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=ko.exactMatch(r.multiaddr),a=ko.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Cu.exactMatch(r.multiaddr),u=Cu.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let f=_u.exactMatch(r.multiaddr),l=_u.exactMatch(t.multiaddr);if(f&&!l)return-1;if(!f&&l)return 1;let d=Bu.exactMatch(r.multiaddr),h=Bu.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function Mb(r,t){let e=Lu(r.multiaddr),n=Lu(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Ub(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Ob(r,t){let e=To.exactMatch(r.multiaddr),n=To.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Jp(r){return r.sort(Rb).sort(Ub).sort(Ob).sort(Mb)}async function Qp(r,t){let e=!1;for(let o of gn.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}var ba={maxParallelDials:fa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:_r}},xa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??ba.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??ba.maxDialQueueLength,this.dialTimeout=e.dialTimeout??ba.dialTimeout,this.connections=e.connections??new Ue,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,ot(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(e.resolvers??{}))gn.set(n,o);this.queue=new wa({concurrency:e.maxParallelDials??ba.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==te.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,ot(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=la(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}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())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new dt("dial-queue:start-dial"));let c=Ve([this.shutDownController.signal,a.signal]);ot(1/0,c);let u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new dt("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:e.priority??Ru,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(l=>({multiaddr:rt(l),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new $r("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new So("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let l=await this.components.peerStore.get(t);o.push(...l.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let l=await this.components.peerRouting.findPeer(t);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",t,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await 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(t!=null){let l=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new 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",t??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!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(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var im=hr(om(),1);var Vb=Object.prototype.toString,Hb=r=>Vb.call(r)==="[object Error]",Kb=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&&Hb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Kb.has(r.message):!1}var Uu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},sm=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Ou(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=im.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Uu)throw c.originalError;if(c instanceof TypeError&&!Mu(c))throw c;if(sm(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){sm(u,a,t),i(),n(u)}}})})}var Ea=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new va({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.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(t){if(!this.started)return;let e=await this.peerStore.get(t);am(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Ou(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(Za)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>am(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function am(r){for(let t of r.tags.keys())if(t.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(t,e={}){if(this.maxConnections=e.maxConnections??Fu.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Ue,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>rt(n)),this.deny=(e.deny??[]).map(n=>rt(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Fu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ca({points:e.inboundConnectionThreshold??Fu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ha({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new xa(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??fa,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??5e3,resolvers:e.resolvers??{dnsaddr:_r},connections:this.connections}),this.reconnectQueue=new Ea({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),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 t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),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:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.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:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new xe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=la(t);if(this.peerId.equals(n))throw new qr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.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),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Ke("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>rt(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var kn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(t){this.timespan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timespan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var zb=1.2,Gb=2,Wb=2e3,Sa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new kn(t.interval??5e3),this.failure=new kn(t.interval??5e3),this.next=new kn(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Gb,this.timeoutMultiplier=t.timeoutMultiplier??zb,this.minTimeout=t.minTimeout??Wb,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=Ve([t.signal,n]);return ot(1/0,o,n),o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var Vu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ht(),this.haveNext=ht()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ht(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ht(),await ur(this.readNext.promise,e?.signal,e)}};function cm(){return new Vu}var _a=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Hu=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ku=class extends Hu{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ba(r,t){let e=cm();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new wt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new 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 wt: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 e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var jb=1e4,Zb="1.0.0",Xb="ping",Yb="ipfs",lm=32,Jb=!0,Ca=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Yb}/${Xb}/${Zb}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??jb,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Jb,this.timeout=new Sa({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Pn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,ot(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Ba(o);e=Date.now(),await Promise.all([s.write(ln(lm),{signal:n}),s.read(lm,{signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Qb(r){return r[Symbol.asyncIterator]!=null}function tx(...r){let t=[];for(let e of r)Qb(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=pa({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Lo=tx;var Ia=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");let n=this,o=new Cr;for await(let s of Lo(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new Sn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new xe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new xe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var ka=globalThis.CustomEvent??Event;async function*qu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,s=[],i=ht(),a=ht(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=ht(),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=ht(),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(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new Ao("No peer routers available");if(t.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(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Vo}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Ao("No peer routers available");let n=this,o=tu(1024);for await(let s of qu(async function*(){let i=Lo(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var La=class extends ve{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ot(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ot(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Ve([this.shutdownController.signal,t?.signal]);ot(1/0,e);try{for(;;)this.needNext?.resolve(),this.needNext=ht(),yield(await Cn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ot(1/0,this.walkController.signal);let t=Ve([this.walkController.signal,this.shutdownController.signal]);ot(1/0,t);let e=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:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ur(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var $u=32,zu=64,Na=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Zi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t))throw new Xi(`Handler already registered for protocol ${t}`);let o=Ai.bind({ignoreUndefined:!0})({maxInboundStreams:$u,maxOutboundStreams:zu},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,e){if(e==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Gu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function um(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Gu({name:t,metrics:e}):n=new Map,n}var Pa=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=um({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??He.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new R("Transport must have a valid tag");if(this.transports.has(e))throw new R(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new Qi(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new xe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(t),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){e.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==He.NO_FATAL)throw new Dr(`Transport (${n}) could not listen on any available address`)}if(e.length===this.transports.size){let n=`no valid addresses were provided for transports [${e.join(", ")}]`;if(this.faultTolerance===He.FATAL_ALL)throw new Dr(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var _t="/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,t={}){let e=Ba(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=pt(t.maxDataLength));let n=t?.lengthDecoder??ie,o=t?.lengthEncoder??kt;return{read:async i=>{let a=-1,c=new wt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Da("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ma("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ra("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new wt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new wt(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var ex=P(`
|
|
7
|
+
`);async function Fr(r,t,e){await r.write(t,e)}async function fm(r,t,e){await r.writeV(t,e)}async function rx(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==ex[0])throw t.log.error("Invalid mss message - missing newline",e),new qo("Missing newline");return e.sublist(0,-1)}async function fr(r,t){let e=await rx(r,t);return et(e.subarray())}async function Po(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return nx(r,t[0],e);let n=No(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',_t,o);let s=P(`${_t}
|
|
8
8
|
`),i=P(`${o}
|
|
9
|
-
`);await fm(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await
|
|
10
|
-
`),e),e.log.trace("select: reading protocol response");let u=await
|
|
9
|
+
`);await fm(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await fr(n,e);if(e.log.trace('select: read "%s"',a),a===_t&&(e.log.trace("select: reading protocol response"),a=await fr(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Fr(n,P(`${c}
|
|
10
|
+
`),e),e.log.trace("select: reading protocol response");let u=await fr(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new Nn("protocol selection failed")}function nx(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ht(),c=!1,u=!1,f=ht(),l=!1,d=!1,h=ht(),p=No({sink:n,source:o},{...e,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,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',_t,t,A.byteLength);let _=`${t}
|
|
11
11
|
`;yield new wt(Uint8Array.from([19]),P(`${_t}
|
|
12
12
|
`),kt(_.length),P(_),A).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',_t,t,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,v)})}x=!0}x||await m()}())};async function m(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await g()),l||(e.log.trace("optimistic: doing read protocol for %s stream",t),await w())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',_t,t),await p.writeV([P(`${_t}
|
|
13
13
|
`),P(`${t}
|
|
14
|
-
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',_t,t)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let b=await
|
|
15
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',_t,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await
|
|
16
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new wt(...t.map(i=>
|
|
14
|
+
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',_t,t)}finally{c=!0,u=!1,f.resolve()}}async function w(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let b=await fr(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',b),b===_t&&(b=await fr(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',b,t),b!==t)throw new Nn("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async y=>{s||await m().catch(x=>{e.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=>{s||await m().catch(x=>{e.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):(s=!0,i=!1,a.resolve()),await b(y)}}return{stream:r,protocol:t}}function Ua(r){return r[Symbol.asyncIterator]!=null}var Oa=r=>{let t=pt(r),e=Ct(t);return kt(r,e),Oa.bytes=t,e};Oa.bytes=0;function Fa(r,t){t=t??{};let e=t.lengthEncoder??Oa;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ua(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Fa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Oa;return new wt(e(r.byteLength),r)};var Va=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ha=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ka=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ox=8,sx=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Zu=r=>{let t=ie(r);return Zu.bytes=pt(t),t};Zu.bytes=0;function ju(r,t){let e=new wt,n=Vr.LENGTH,o=-1,s=t?.lengthDecoder??Zu,i=t?.maxLengthLength??ox,a=t?.maxDataLength??sx;function*c(){for(;e.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(e),o<0)throw new Va("Invalid message length");if(o>a)throw new Ha("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Vr.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new Ka("Message length length too long");break}throw u}if(n===Vr.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Vr.LENGTH}}}return Ua(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Do("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Do("Unexpected end of input")}()}ju.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return ju(n,{...t??{},onLength:s=>{e=s}})};async function Ro(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=No(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await fr(n,e);if(e.log.trace('handle: read "%s"',o),o===_t){e.log.trace('handle: respond with "%s" for "%s"',_t,o),await Fr(n,P(`${_t}
|
|
15
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',_t,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Fr(n,P(`${o}
|
|
16
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new wt(...t.map(i=>Fa.single(P(`${i}
|
|
17
17
|
`))),P(`
|
|
18
|
-
`));e.log.trace('handle: respond with "%s" for %s',t,o),await
|
|
19
|
-
`),e),e.log('handle: responded with "na" for "%s"',o)}}var ax=500,Xu=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[sf]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Fo("the connection is being closed");if(this.status==="closed")throw new Hr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new $r("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(ax);ot(1/0,e),t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function dm(r){return new Xu(r)}function ux(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return $u}function fx(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??zu}function pm(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ha=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=e.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??2e3,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Zi(`The multiaddr connection is blocked by gater.${t}`)}async upgradeInbound(t,e={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(t),!n)throw new Xi("Connection denied");await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",e)}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e={}){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;return n!=null&&(o=we(n),await this.shouldBlockConnection("denyOutboundConnection",o,t)),await this._performUpgrade(t,"outbound",e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,u=AbortSignal.timeout(e==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ve([u,n.signal]);ot(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),l=await d.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(e==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Ke(`${e} connection that skipped encryption must have a peer id`);let h=we(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new Kr("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}finally{f.clear()}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);ot(1/0,g);let{stream:w,protocol:b}=await Do(p,m,{signal:g,log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",b);let y=ux(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);ot(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=fx(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",t.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:e,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(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new $r("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Do(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Dr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Dr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Po(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Dr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Dr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Po(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Rr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Do(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Rr(String(s))}}};var mm="2.3.1-339b7df88",gm="js-libp2p";var Ka=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},ot(1/0,e),this.peerId=t.peerId,this.logger=t.logger??Ci(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Dp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:gm,version:mm},logger:this.logger,events:e,datastore:t.datastore??new Ki,connectionGater:zp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",Lp(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new Ha(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:t.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new La(this.components,t.transportManager)),this.configureComponent("connectionManager",new va(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new _a(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Ta(this.components)),this.configureComponent("addressManager",new qi(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ia(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ba(this.components,{routers:i})),this.configureComponent("randomWalk",new ka(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[$a]!=null&&(this.log("registering service %s for content routing",a),i.push(u[$a])),u[Ga]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ga])),u[za]!=null&&(this.log("registering service %s for peer discovery",a),u[za].addEventListener?.("peer",f=>{this.#t(f)}))}Mp(o)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Br;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new D("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){ir(t)&&(t=we(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Vt([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=un(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function dx(r={}){r.privateKey??=await Bd("Ed25519");let t=new Ka({...await ap(r),peerId:Td(r.privateKey)});return r.start!==!1&&await t.start(),t}return Tm(px);})();
|
|
18
|
+
`));e.log.trace('handle: respond with "%s" for %s',t,o),await Fr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Fr(n,P(`na
|
|
19
|
+
`),e),e.log('handle: responded with "na" for "%s"',o)}}var ax=500,Xu=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[sf]=!0;get streams(){return this._getStreams()}async newStream(t,e){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(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(ax);ot(1/0,e),t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function dm(r){return new Xu(r)}function ux(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return $u}function fx(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??zu}function pm(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var qa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=e.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??2e3,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Yi(`The multiaddr connection is blocked by gater.${t}`)}async upgradeInbound(t,e={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(t),!n)throw new Ji("Connection denied");await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",e)}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e={}){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;return n!=null&&(o=we(n),await this.shouldBlockConnection("denyOutboundConnection",o,t)),await this._performUpgrade(t,"outbound",e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,u=AbortSignal.timeout(e==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ve([u,n.signal]);ot(1/0,u,f),n.signal=f,this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),l=await d.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(e==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let d={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Ke(`${e} connection that skipped encryption must have a peer id`);let h=we(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new qr("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}finally{f.clear()}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);ot(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=ux(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);ot(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=fx(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",t.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:e,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(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Ro(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Mr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Mr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Po(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Mr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Mr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Po(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Rr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Ro(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Rr(String(s))}}};var mm="2.3.1-406b3916c",gm="js-libp2p";var $a=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},ot(1/0,e),this.peerId=t.peerId,this.logger=t.logger??Ci(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Rp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:gm,version:mm},logger:this.logger,events:e,datastore:t.datastore??new Ki,connectionGater:zp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",Lp(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new qa(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:t.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new Pa(this.components,t.transportManager)),this.configureComponent("connectionManager",new Aa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ca(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Na(this.components)),this.configureComponent("addressManager",new zi(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ta(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ia(this.components,{routers:i})),this.configureComponent("randomWalk",new La(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[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.#t(f)}))}Mp(o)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Cr;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new R("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new R("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){ar(t)&&(t=we(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Vt([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=fn(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function dx(r={}){r.privateKey??=await Bd("Ed25519");let t=new $a({...await ap(r),peerId:Td(r.privateKey)});return r.start!==!1&&await t.start(),t}return Tm(px);})();
|
|
20
20
|
/*! Bundled license information:
|
|
21
21
|
|
|
22
22
|
pvtsutils/build/index.js:
|