libp2p 1.9.3-dd7b329c4 → 1.9.4-df330695a
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 +15 -16
- package/dist/src/components.d.ts.map +1 -1
- package/dist/src/components.js +4 -3
- package/dist/src/components.js.map +1 -1
- package/dist/src/config.d.ts +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +2 -7
- package/dist/src/config.js.map +1 -1
- package/dist/src/connection/index.d.ts +3 -3
- package/dist/src/connection/index.d.ts.map +1 -1
- package/dist/src/connection/index.js +7 -7
- package/dist/src/connection/index.js.map +1 -1
- package/dist/src/connection-manager/connection-pruner.js +1 -1
- package/dist/src/connection-manager/constants.browser.d.ts +0 -8
- package/dist/src/connection-manager/constants.browser.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.browser.js +0 -8
- package/dist/src/connection-manager/constants.browser.js.map +1 -1
- package/dist/src/connection-manager/constants.d.ts +0 -8
- package/dist/src/connection-manager/constants.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.defaults.d.ts +12 -22
- package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.defaults.js +12 -22
- package/dist/src/connection-manager/constants.defaults.js.map +1 -1
- package/dist/src/connection-manager/constants.js +0 -8
- package/dist/src/connection-manager/constants.js.map +1 -1
- package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +29 -15
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +47 -50
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +23 -57
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/connection-manager/reconnect-queue.d.ts +35 -0
- package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -0
- package/dist/src/connection-manager/reconnect-queue.js +104 -0
- package/dist/src/connection-manager/reconnect-queue.js.map +1 -0
- package/dist/src/connection-monitor.js +1 -1
- package/dist/src/connection-monitor.js.map +1 -1
- package/dist/src/content-routing.js +6 -6
- package/dist/src/content-routing.js.map +1 -1
- package/dist/src/errors.d.ts +41 -61
- package/dist/src/errors.d.ts.map +1 -1
- package/dist/src/errors.js +84 -63
- package/dist/src/errors.js.map +1 -1
- package/dist/src/get-peer.d.ts.map +1 -1
- package/dist/src/get-peer.js +4 -5
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/index.d.ts +25 -7
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +9 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/libp2p.d.ts +11 -10
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js +11 -29
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/peer-routing.js +8 -8
- package/dist/src/peer-routing.js.map +1 -1
- package/dist/src/registrar.js +7 -7
- package/dist/src/registrar.js.map +1 -1
- package/dist/src/transport-manager.d.ts.map +1 -1
- package/dist/src/transport-manager.js +15 -23
- package/dist/src/transport-manager.js.map +1 -1
- package/dist/src/upgrader.d.ts +4 -4
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +35 -35
- package/dist/src/upgrader.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +20 -20
- package/src/components.ts +4 -3
- package/src/config.ts +4 -10
- package/src/connection/index.ts +9 -9
- package/src/connection-manager/connection-pruner.ts +1 -1
- package/src/connection-manager/constants.browser.ts +0 -10
- package/src/connection-manager/constants.defaults.ts +14 -27
- package/src/connection-manager/constants.ts +0 -10
- package/src/connection-manager/dial-queue.ts +30 -15
- package/src/connection-manager/index.ts +80 -118
- package/src/connection-manager/reconnect-queue.ts +134 -0
- package/src/connection-monitor.ts +1 -1
- package/src/content-routing.ts +6 -6
- package/src/errors.ts +96 -61
- package/src/get-peer.ts +4 -5
- package/src/index.ts +40 -10
- package/src/libp2p.ts +20 -34
- package/src/peer-routing.ts +8 -8
- package/src/registrar.ts +7 -7
- package/src/transport-manager.ts +15 -23
- package/src/upgrader.ts +37 -38
- package/src/version.ts +1 -1
- package/dist/src/connection-manager/auto-dial.d.ts +0 -47
- package/dist/src/connection-manager/auto-dial.d.ts.map +0 -1
- package/dist/src/connection-manager/auto-dial.js +0 -223
- package/dist/src/connection-manager/auto-dial.js.map +0 -1
- package/src/connection-manager/auto-dial.ts +0 -285
package/dist/index.min.js
CHANGED
|
@@ -1,23 +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 wp=Object.create;var ko=Object.defineProperty;var bp=Object.getOwnPropertyDescriptor;var Ep=Object.getOwnPropertyNames;var xp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty;var At=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},fu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ep(e))!vp.call(r,o)&&o!==t&&ko(r,o,{get:()=>e[o],enumerable:!(n=bp(e,o))||n.enumerable});return r};var gr=(r,e,t)=>(t=r!=null?wp(xp(r)):{},fu(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r)),_p=r=>fu(ko({},"__esModule",{value:!0}),r);var mf=At(cn=>{"use strict";var Jg="[object ArrayBuffer]",Lt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Jg}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},bc="string",e0=/^[0-9a-f]+$/i,t0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,r0=/^[a-zA-Z0-9-_]+$/,Jo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Lt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},nt=class{static toString(e,t=!1){let n=Lt.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},es=class r{static isHex(e){return typeof e===bc&&e0.test(e)}static isBase64(e){return typeof e===bc&&t0.test(e)}static isBase64Url(e){return typeof e===bc&&r0.test(e)}static ToString(e,t="utf8"){let n=Lt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return nt.toString(n,!0);case"utf16":case"utf16be":return nt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return nt.fromString(e,!0);case"utf16":case"utf16be":return nt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Lt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Jo.fromString(e);case"utf16":case"utf16be":return nt.fromString(e);case"utf16le":case"usc2":return nt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Jo.toString(e);case"utf16":case"utf16be":return nt.toString(e);case"utf16le":case"usc2":return nt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Lt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Lt.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return nt.toString(e,t)}static FromUtf16String(e,t=!1){return nt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};es.DEFAULT_UTF8_ENCODING="utf8";function n0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function o0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function s0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}cn.BufferSourceConverter=Lt;cn.Convert=es;cn.assign=n0;cn.combine=o0;cn.isEqual=s0});var Bh=At((uo,Gs)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,E=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,E),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,E),y^=b}return y^=h.length,y=i(y),y>>>0},t.x86.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,E=p,A=0,R=0,v=0,I=0,N=597399067,ee=2869860233,H=951274213,K=2716044179,O=0;O<g;O=O+16)A=h[O]|h[O+1]<<8|h[O+2]<<16|h[O+3]<<24,R=h[O+4]|h[O+5]<<8|h[O+6]<<16|h[O+7]<<24,v=h[O+8]|h[O+9]<<8|h[O+10]<<16|h[O+11]<<24,I=h[O+12]|h[O+13]<<8|h[O+14]<<16|h[O+15]<<24,A=o(A,N),A=s(A,15),A=o(A,ee),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,R=o(R,ee),R=s(R,16),R=o(R,H),b^=R,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,H),v=s(v,17),v=o(v,K),w^=v,w=s(w,15),w+=E,w=o(w,5)+2530024501,I=o(I,K),I=s(I,18),I=o(I,N),E^=I,E=s(E,13),E+=y,E=o(E,5)+850148119;switch(A=0,R=0,v=0,I=0,m){case 15:I^=h[O+14]<<16;case 14:I^=h[O+13]<<8;case 13:I^=h[O+12],I=o(I,K),I=s(I,18),I=o(I,N),E^=I;case 12:v^=h[O+11]<<24;case 11:v^=h[O+10]<<16;case 10:v^=h[O+9]<<8;case 9:v^=h[O+8],v=o(v,H),v=s(v,17),v=o(v,K),w^=v;case 8:R^=h[O+7]<<24;case 7:R^=h[O+6]<<16;case 6:R^=h[O+5]<<8;case 5:R^=h[O+4],R=o(R,ee),R=s(R,16),R=o(R,H),b^=R;case 4:A^=h[O+3]<<24;case 3:A^=h[O+2]<<16;case 2:A^=h[O+1]<<8;case 1:A^=h[O],A=o(A,N),A=s(A,15),A=o(A,ee),y^=A}return y^=h.length,b^=h.length,w^=h.length,E^=h.length,y+=b,y+=w,y+=E,b+=y,w+=y,E+=y,y=i(y),b=i(b),w=i(w),E=i(E),y+=b,y+=w,y+=E,b+=y,w+=y,E+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],E=[0,0],A=[2277735313,289559509],R=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],E=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,R),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),E=c(E,R),E=u(E,33),E=c(E,A),b=l(b,E),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],E=[0,0],m){case 15:E=l(E,f([0,h[v+14]],48));case 14:E=l(E,f([0,h[v+13]],40));case 13:E=l(E,f([0,h[v+12]],32));case 12:E=l(E,f([0,h[v+11]],24));case 11:E=l(E,f([0,h[v+10]],16));case 10:E=l(E,f([0,h[v+9]],8));case 9:E=l(E,[0,h[v+8]]),E=c(E,R),E=u(E,33),E=c(E,A),b=l(b,E);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,R),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof uo<"u"?(typeof Gs<"u"&&Gs.exports&&(uo=Gs.exports=t),uo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(uo)});var kh=At((t_,Ch)=>{Ch.exports=Bh()});var td=At((k2,ol)=>{"use strict";var Cy=Object.prototype.hasOwnProperty,qe="~";function yo(){}Object.create&&(yo.prototype=Object.create(null),new yo().__proto__||(qe=!1));function ky(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ed(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new ky(t,n||r,o),i=qe?qe+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Js(r,e){--r._eventsCount===0?r._events=new yo:delete r._events[e]}function Ue(){this._events=new yo,this._eventsCount=0}Ue.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Cy.call(t,n)&&e.push(qe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ue.prototype.listeners=function(e){var t=qe?qe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ue.prototype.listenerCount=function(e){var t=qe?qe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ue.prototype.emit=function(e,t,n,o,s,i){var a=qe?qe+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Ue.prototype.on=function(e,t,n){return ed(this,e,t,n,!1)};Ue.prototype.once=function(e,t,n){return ed(this,e,t,n,!0)};Ue.prototype.removeListener=function(e,t,n,o){var s=qe?qe+e:e;if(!this._events[s])return this;if(!t)return Js(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Js(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Js(this,s)}return this};Ue.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Js(this,t)):(this._events=new yo,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=qe;Ue.EventEmitter=Ue;typeof ol<"u"&&(ol.exports=Ue)});var gd=At((XS,md)=>{"use strict";function pd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function jy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return pd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),pd(new o,t)}}md.exports=jy});var vd=At(xo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),xo.ip2long=i,xo.long2ip=a,xo.Netmask=r}).call(xo)});var Pd=At((oI,Dd)=>{Dd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Vd=At((vI,Fd)=>{"use strict";Fd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Gd=At((qd,zd)=>{"use strict";var Ei=Vd(),{hasOwnProperty:Hd}=Object.prototype,{propertyIsEnumerable:vw}=Object,In=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),_w=qd,Kd={concatArrays:!1,ignoreUndefined:!1},xi=r=>{let e=[];for(let t in r)Hd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)vw.call(r,n)&&e.push(n)}return e};function Tn(r){return Array.isArray(r)?Aw(r):Ei(r)?Sw(r):r}function Aw(r){let e=r.slice(0,0);return xi(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}function Sw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return xi(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}var $d=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?In(r,o,Dl(r[o],e[o],n)):In(r,o,Tn(e[o])))}),r),Rw=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Hd.call(s,a)&&(i.push(String(a)),s===r?In(n,o++,s[a]):In(n,o++,Tn(s[a])));n=$d(n,s,xi(s).filter(a=>!i.includes(a)),t)}),n};function Dl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Rw(r,e,t):!Ei(e)||!Ei(r)?Tn(e):$d(r,e,xi(e),t)}zd.exports=function(...r){let e=Dl(Tn(Kd),this!==_w&&this||{},Kd),t={_:{}};for(let n of r)if(n!==void 0){if(!Ei(n))throw new TypeError("`"+n+"` is not an Option Object");t=Dl(t,{_:n},e)}return t._}});var ob={};ve(ob,{createLibp2p:()=>nb});var hu=Symbol.for("@libp2p/connection");var ca=Symbol.for("@libp2p/content-routing");var la=Symbol.for("@libp2p/peer-discovery");var No=Symbol.for("@libp2p/peer-id");function Lo(r){return r!=null&&!!r[No]}var ua=Symbol.for("@libp2p/peer-routing");var du="keep-alive";var hb=Symbol.for("@libp2p/transport");var zt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(zt||(zt={}));var Gt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},x=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},Do=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var Po="ERR_TIMEOUT";var ie=(r,...e)=>{try{[...e]}catch{}};var St=class extends EventTarget{#e=new Map;constructor(){super(),ie(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new fa(e,t))}},fa=globalThis.CustomEvent;function pu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Pn=Symbol.for("@libp2p/service-capabilities"),ha=Symbol.for("@libp2p/service-dependencies");var yc={};ve(yc,{Ed25519PrivateKey:()=>Tr,Ed25519PublicKey:()=>Gn,generateKeyPair:()=>Xg,generateKeyPairFromSeed:()=>pf,unmarshalEd25519PrivateKey:()=>jg,unmarshalEd25519PublicKey:()=>Wg});var ya={};ve(ya,{base58btc:()=>ae,base58flickr:()=>Bp});var Hb=new Uint8Array(0);function mu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Rt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function gu(r){return new TextEncoder().encode(r)}function yu(r){return new TextDecoder().decode(r)}function Ap(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,E=new Uint8Array(w);y!==b;){for(var A=p[y],R=0,v=w-1;(A!==0||R<g)&&v!==-1;v--,R++)A+=256*E[v]>>>0,E[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=R,y++}for(var I=w-g;I!==w&&E[I]===0;)I++;for(var N=c.repeat(m);I<w;++I)N+=r.charAt(E[I]);return N}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var E=t[p.charCodeAt(m)];if(E===255)return;for(var A=0,R=b-1;(E!==0||A<y)&&R!==-1;R--,A++)E+=a*w[R]>>>0,w[R]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var I=new Uint8Array(g+(b-v)),N=g;v!==b;)I[N++]=w[v++];return I}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Sp=Ap,Rp=Sp,bu=Rp;var da=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Eu(this,e)}},ma=class{decoders;constructor(e){this.decoders=e}or(e){return Eu(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Eu(r,e){return new ma({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ga=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new da(e,t,n),this.decoder=new pa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function qr({name:r,prefix:e,encode:t,decode:n}){return new ga(r,e,t,n)}function Yt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=bu(t,r);return qr({prefix:e,name:r,encode:n,decode:s=>Rt(o(s))})}function Ip(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Tp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return qr({prefix:e,name:r,encode(o){return Tp(o,n,t)},decode(o){return Ip(o,n,t,r)}})}var ae=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bp=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ba={};ve(ba,{identity:()=>It});var Cp=_u,xu=128,kp=127,Np=~kp,Lp=Math.pow(2,31);function _u(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Lp;)e[t++]=r&255|xu,r/=128;for(;r&Np;)e[t++]=r&255|xu,r>>>=7;return e[t]=r|0,_u.bytes=t-n+1,e}var Dp=wa,Pp=128,vu=127;function wa(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wa.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&vu)<<o:(i&vu)*Math.pow(2,o),o+=7}while(i>=Pp);return wa.bytes=s-n,t}var Op=Math.pow(2,7),Up=Math.pow(2,14),Mp=Math.pow(2,21),Fp=Math.pow(2,28),Vp=Math.pow(2,35),Kp=Math.pow(2,42),Hp=Math.pow(2,49),$p=Math.pow(2,56),qp=Math.pow(2,63),zp=function(r){return r<Op?1:r<Up?2:r<Mp?3:r<Fp?4:r<Vp?5:r<Kp?6:r<Hp?7:r<$p?8:r<qp?9:10},Gp={encode:Cp,decode:Dp,encodingLength:zp},Yp=Gp,On=Yp;function Un(r,e=0){return[On.decode(r,e),On.decode.bytes]}function zr(r,e,t=0){return On.encode(r,e,t),e}function Gr(r){return On.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=Gr(r),o=n+Gr(t),s=new Uint8Array(o+t);return zr(r,s,0),zr(t,s,n),s.set(e,o),new Yr(r,t,e,s)}function yr(r){let e=Rt(r),[t,n]=Un(e),[o,s]=Un(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yr(t,o,i,e)}function Au(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&mu(r.bytes,t.bytes)}}var Yr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Su=0,jp="identity",Ru=Rt;function Wp(r){return mt(Su,Ru(r))}var It={code:Su,name:jp,encode:Ru,digest:Wp};var va={};ve(va,{sha256:()=>Re,sha512:()=>Xp});function xa({name:r,code:e,encode:t}){return new Ea(r,e,t)}var Ea=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?mt(this.code,t):t.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Tu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=xa({name:"sha2-256",code:18,encode:Tu("SHA-256")}),Xp=xa({name:"sha2-512",code:19,encode:Tu("SHA-512")});function te(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function st(r=0){return new Uint8Array(r)}function Ne(r=0){return new Uint8Array(r)}function Ie(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ne(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var _a={};ve(_a,{base10:()=>Zp});var Zp=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var Aa={};ve(Aa,{base16:()=>Qp,base16upper:()=>Jp});var Qp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Sa={};ve(Sa,{base2:()=>em});var em=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ra={};ve(Ra,{base256emoji:()=>sm});var Bu=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}"),tm=Bu.reduce((r,e,t)=>(r[t]=e,r),[]),rm=Bu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function nm(r){return r.reduce((e,t)=>(e+=tm[t],e),"")}function om(r){let e=[];for(let t of r){let n=rm[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var sm=qr({prefix:"\u{1F680}",name:"base256emoji",encode:nm,decode:om});var Ia={};ve(Ia,{base32:()=>We,base32hex:()=>lm,base32hexpad:()=>fm,base32hexpadupper:()=>hm,base32hexupper:()=>um,base32pad:()=>am,base32padupper:()=>cm,base32upper:()=>im,base32z:()=>dm});var We=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),im=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),am=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lm=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),um=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),dm=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ta={};ve(Ta,{base36:()=>pm,base36upper:()=>mm});var pm=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mm=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ca={};ve(Ca,{base64:()=>Mn,base64pad:()=>gm,base64url:()=>Ba,base64urlpad:()=>ym});var Mn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ba=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ym=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ka={};ve(ka,{base8:()=>wm});var wm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Na={};ve(Na,{identity:()=>bm});var bm=qr({prefix:"\0",name:"identity",encode:r=>yu(r),decode:r=>gu(r)});var gE=new TextEncoder,yE=new TextDecoder;function Cu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _m(t,La(r),e??ae.encoder);default:return Am(t,La(r),e??We.encoder)}}var ku=new WeakMap;function La(r){let e=ku.get(r);if(e==null){let t=new Map;return ku.set(r,t),t}return e}var et=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Sm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=mt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Au(e.multihash,n.multihash)}toString(e){return Cu(this,e)}toJSON(){return{"/":Cu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Nu(n,o,s.bytes))}else if(t[Rm]===!0){let{version:n,multihash:o,code:s}=t,i=yr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Nu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Rt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Yr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=Un(e.subarray(t));return t+=d,l},o=n(),s=Fn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=vm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return La(s).set(n,e),s}};function vm(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function _m(r,e,t){let{prefix:n}=t;if(n!==ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Am(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Fn=112,Sm=18;function Nu(r,e,t){let n=Gr(r),o=n+Gr(e),s=new Uint8Array(o+t.byteLength);return zr(r,s,0),zr(e,s,n),s.set(t,o),s}var Rm=Symbol.for("@ipld/js-cid/CID");var jt={...Na,...Sa,...ka,..._a,...Aa,...Ia,...Ta,...ya,...Ca,...Ra},LE={...va,...ba};function Du(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lu=Du("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Da=Du("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ne(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Im={utf8:Lu,"utf-8":Lu,hex:jt.base16,latin1:Da,ascii:Da,binary:Da,...jt},Uo=Im;function L(r,e="utf8"){let t=Uo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function tt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function jr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Tm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wr(r,...e){if(!Tm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Mo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");jr(r.outputLen),jr(r.blockLen)}function Xr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Pu(r,e){Wr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var br=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Qr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var YE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Bm=async()=>{};async function Ou(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Bm(),n+=s)}}function Uu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Wt(r){return typeof r=="string"&&(r=Uu(r)),Wr(r),r}function Pa(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Wr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Zr=class{clone(){return this._cloneInto()}},Cm={}.toString;function Mu(r,e){if(e!==void 0&&Cm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Fo(r){let e=n=>r().update(Wt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Jr(r=32){if(br&&typeof br.getRandomValues=="function")return br.getRandomValues(new Uint8Array(r));if(br&&typeof br.randomBytes=="function")return br.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function km(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Fu=(r,e,t)=>r&e^~r&t,Vu=(r,e,t)=>r&e^r&t^e&t,en=class extends Zr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Qr(this.buffer)}update(e){Xr(this);let{view:t,buffer:n,blockLen:o}=this;e=Wt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Qr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xr(this),Pu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;km(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Qr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Vo=BigInt(4294967295),Oa=BigInt(32);function Ku(r,e=!1){return e?{h:Number(r&Vo),l:Number(r>>Oa&Vo)}:{h:Number(r>>Oa&Vo)|0,l:Number(r&Vo)|0}}function Nm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Ku(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Lm=(r,e)=>BigInt(r>>>0)<<Oa|BigInt(e>>>0),Dm=(r,e,t)=>r>>>t,Pm=(r,e,t)=>r<<32-t|e>>>t,Om=(r,e,t)=>r>>>t|e<<32-t,Um=(r,e,t)=>r<<32-t|e>>>t,Mm=(r,e,t)=>r<<64-t|e>>>t-32,Fm=(r,e,t)=>r>>>t-32|e<<64-t,Vm=(r,e)=>e,Km=(r,e)=>r,Hm=(r,e,t)=>r<<t|e>>>32-t,$m=(r,e,t)=>e<<t|r>>>32-t,qm=(r,e,t)=>e<<t-32|r>>>64-t,zm=(r,e,t)=>r<<t-32|e>>>64-t;function Gm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ym=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Wm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Xm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Zm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Qm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Jm={fromBig:Ku,split:Nm,toBig:Lm,shrSH:Dm,shrSL:Pm,rotrSH:Om,rotrSL:Um,rotrBH:Mm,rotrBL:Fm,rotr32H:Vm,rotr32L:Km,rotlSH:Hm,rotlSL:$m,rotlBH:qm,rotlBL:zm,add:Gm,add3L:Ym,add3H:jm,add4L:Wm,add4H:Xm,add5H:Qm,add5L:Zm},F=Jm;var[eg,tg]=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))),Xt=new Uint32Array(80),Zt=new Uint32Array(80),Ua=class extends en{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)Xt[w]=e.getUint32(t),Zt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let E=Xt[w-15]|0,A=Zt[w-15]|0,R=F.rotrSH(E,A,1)^F.rotrSH(E,A,8)^F.shrSH(E,A,7),v=F.rotrSL(E,A,1)^F.rotrSL(E,A,8)^F.shrSL(E,A,7),I=Xt[w-2]|0,N=Zt[w-2]|0,ee=F.rotrSH(I,N,19)^F.rotrBH(I,N,61)^F.shrSH(I,N,6),H=F.rotrSL(I,N,19)^F.rotrBL(I,N,61)^F.shrSL(I,N,6),K=F.add4L(v,H,Zt[w-7],Zt[w-16]),O=F.add4H(K,R,ee,Xt[w-7],Xt[w-16]);Xt[w]=O|0,Zt[w]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let E=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),R=l&h^~l&m,v=d&p^~d&g,I=F.add5L(b,A,v,tg[w],Zt[w]),N=F.add5H(I,y,E,R,eg[w],Xt[w]),ee=I|0,H=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),K=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),O=n&s^n&a^s&a,B=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=F.add(u|0,f|0,N|0,ee|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=F.add3L(ee,K,B);n=F.add3H(D,N,H,O),o=D|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:y,l:b}=F.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){Xt.fill(0),Zt.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 Vn=Fo(()=>new Ua);var Ho={};ve(Ho,{aInRange:()=>Ge,abool:()=>at,abytes:()=>tn,bitGet:()=>ag,bitLen:()=>Ha,bitMask:()=>Hn,bitSet:()=>cg,bytesToHex:()=>Bt,bytesToNumberBE:()=>Ct,bytesToNumberLE:()=>Jt,concatBytes:()=>kt,createHmacDrbg:()=>$a,ensureBytes:()=>le,equalBytes:()=>sg,hexToBytes:()=>xr,hexToNumber:()=>Ka,inRange:()=>Kn,isBytes:()=>Qt,memoized:()=>_r,notImplemented:()=>ug,numberToBytesBE:()=>er,numberToBytesLE:()=>vr,numberToHexUnpadded:()=>Er,numberToVarBytesBE:()=>og,utf8ToBytes:()=>ig,validateObject:()=>gt});var Va=BigInt(0),Ko=BigInt(1),rg=BigInt(2);function Qt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function tn(r){if(!Qt(r))throw new Error("Uint8Array expected")}function at(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var ng=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){tn(r);let e="";for(let t=0;t<r.length;t++)e+=ng[r[t]];return e}function Er(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ka(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var Tt={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Hu(r){if(r>=Tt._0&&r<=Tt._9)return r-Tt._0;if(r>=Tt._A&&r<=Tt._F)return r-(Tt._A-10);if(r>=Tt._a&&r<=Tt._f)return r-(Tt._a-10)}function xr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Hu(r.charCodeAt(s)),a=Hu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ct(r){return Ka(Bt(r))}function Jt(r){return tn(r),Ka(Bt(Uint8Array.from(r).reverse()))}function er(r,e){return xr(r.toString(16).padStart(e*2,"0"))}function vr(r,e){return er(r,e).reverse()}function og(r){return xr(Er(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=xr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Qt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function kt(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];tn(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function sg(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ig(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Ma=r=>typeof r=="bigint"&&Va<=r;function Kn(r,e,t){return Ma(r)&&Ma(e)&&Ma(t)&&e<=r&&r<t}function Ge(r,e,t,n){if(!Kn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function Ha(r){let e;for(e=0;r>Va;r>>=Ko,e+=1);return e}function ag(r,e){return r>>BigInt(e)&Ko}function cg(r,e,t){return r|(t?Ko:Va)<<BigInt(e)}var Hn=r=>(rg<<BigInt(r-1))-Ko,Fa=r=>new Uint8Array(r),$u=r=>Uint8Array.from(r);function $a(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Fa(r),o=Fa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Fa())=>{o=a($u([0]),l),n=a(),l.length!==0&&(o=a($u([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<e;){n=a();let h=n.slice();d.push(h),l+=n.length}return kt(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var lg={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"||Qt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function gt(r,e,t={}){let n=(o,s,i)=>{let a=lg[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ug=()=>{throw new Error("not implemented")};function _r(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),re=BigInt(1),Ar=BigInt(2),fg=BigInt(3),qa=BigInt(4),qu=BigInt(5),zu=BigInt(8),hg=BigInt(9),dg=BigInt(16);function Z(r,e){let t=r%e;return t>=ge?t:e+t}function pg(r,e,t){if(t<=ge||e<ge)throw new Error("Expected power/modulo > 0");if(t===re)return ge;let n=re;for(;e>ge;)e&re&&(n=n*r%t),r=r*r%t,e>>=re;return n}function ne(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function $o(r,e){if(r===ge||e<=ge)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Z(r,e),n=e,o=ge,s=re,i=re,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==re)throw new Error("invert: does not exist");return Z(o,e)}function mg(r){let e=(r-re)/Ar,t,n,o;for(t=r-re,n=0;t%Ar===ge;t/=Ar,n++);for(o=Ar;o<r&&pg(o,e,r)!==r-re;o++);if(n===1){let i=(r+re)/qa;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+re)/Ar;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,re<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function gg(r){if(r%qa===fg){let e=(r+re)/qa;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%zu===qu){let e=(r-qu)/zu;return function(n,o){let s=n.mul(o,Ar),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Ar),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%dg,mg(r)}var Gu=(r,e)=>(Z(r,e)&re)===re,yg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function za(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=yg.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function wg(r,e,t){if(t<ge)throw new Error("Expected power > 0");if(t===ge)return r.ONE;if(t===re)return e;let n=r.ONE,o=e;for(;t>ge;)t&re&&(n=r.mul(n,o)),o=r.sqr(o),t>>=re;return n}function bg(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Ga(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function tr(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ga(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=gg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Hn(o),ZERO:ge,ONE:re,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&re)===re,neg:c=>Z(-c,r),eql:(c,u)=>c===u,sqr:c=>Z(c*c,r),add:(c,u)=>Z(c+u,r),sub:(c,u)=>Z(c-u,r),mul:(c,u)=>Z(c*u,r),pow:(c,u)=>wg(a,c,u),div:(c,u)=>Z(c*$o(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>$o(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>bg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?vr(c,s):er(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Jt(c):Ct(c)}});return Object.freeze(a)}function Yu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Ya(r){let e=Yu(r);return e+Math.ceil(e/2)}function ju(r,e,t=!1){let n=r.length,o=Yu(e),s=Ya(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Ct(r):Jt(r),a=Z(i,e-re)+re;return t?vr(a,o):er(a,o)}var xg=BigInt(0),ja=BigInt(1),Wa=new WeakMap,Wu=new WeakMap;function qo(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>xg;)i&ja&&(a=a.add(c)),c=c.double(),i>>=ja;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=ja);let b=g,w=g+Math.abs(y)-1,E=m%2!==0,A=y<0;y===0?l=l.add(t(E,i[b])):f=f.add(t(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=Wu.get(s)||1,u=Wa.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Wa.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),Wu.set(s,i),Wa.delete(s)}}}function zo(r,e,t,n){if(!Array.isArray(t)||!Array.isArray(n)||n.length!==t.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!e.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),t.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Ha(BigInt(t.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((e.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(t[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function $n(r){return za(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ga(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),Ye=BigInt(1),Go=BigInt(2),vg=BigInt(8),_g={zip215:!0};function Ag(r){let e=$n(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Xu(r){let e=Ag(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Go<<BigInt(a*8)-Ye,f=t.create,l=tr(e.n,e.nBitLength),d=e.uvRatio||((S,_)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(_))}}catch{return{isValid:!1,value:ct}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,_,T)=>{if(at("phflag",T),_.length||T)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,_){Ge("coordinate "+S,_,ct,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=_r((S,_)=>{let{ex:T,ey:P,ez:U}=S,M=S.is0();_==null&&(_=M?vg:t.inv(U));let $=f(T*_),G=f(P*_),q=f(U*_);if(M)return{x:ct,y:Ye};if(q!==Ye)throw new Error("invZ was invalid");return{x:$,y:G}}),b=_r(S=>{let{a:_,d:T}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:P,ey:U,ez:M,et:$}=S,G=f(P*P),q=f(U*U),X=f(M*M),J=f(X*X),Ee=f(G*_),xe=f(X*f(Ee+q)),Se=f(J+f(T*f(G*q)));if(xe!==Se)throw new Error("bad point: equation left != right (1)");let Me=f(P*U),me=f(M*$);if(Me!==me)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(_,T,P,U){this.ex=_,this.ey=T,this.ez=P,this.et=U,m("x",_),m("y",T),m("z",P),m("t",U),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof w)throw new Error("extended point not allowed");let{x:T,y:P}=_||{};return m("x",T),m("y",P),new w(T,P,Ye,f(T*P))}static normalizeZ(_){let T=t.invertBatch(_.map(P=>P.ez));return _.map((P,U)=>P.toAffine(T[U])).map(w.fromAffine)}static msm(_,T){return zo(w,l,_,T)}_setWindowSize(_){R.setWindowSize(this,_)}assertValidity(){b(this)}equals(_){g(_);let{ex:T,ey:P,ez:U}=this,{ex:M,ey:$,ez:G}=_,q=f(T*G),X=f(M*U),J=f(P*G),Ee=f($*U);return q===X&&J===Ee}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:_}=e,{ex:T,ey:P,ez:U}=this,M=f(T*T),$=f(P*P),G=f(Go*f(U*U)),q=f(_*M),X=T+P,J=f(f(X*X)-M-$),Ee=q+$,xe=Ee-G,Se=q-$,Me=f(J*xe),me=f(Ee*Se),ze=f(J*Se),_t=f(xe*Ee);return new w(Me,me,_t,ze)}add(_){g(_);let{a:T,d:P}=e,{ex:U,ey:M,ez:$,et:G}=this,{ex:q,ey:X,ez:J,et:Ee}=_;if(T===BigInt(-1)){let ou=f((M-U)*(X+q)),su=f((M+U)*(X-q)),aa=f(su-ou);if(aa===ct)return this.double();let iu=f($*Go*Ee),au=f(G*Go*J),cu=au+iu,lu=su+ou,uu=au-iu,pp=f(cu*aa),mp=f(lu*uu),gp=f(cu*uu),yp=f(aa*lu);return new w(pp,mp,yp,gp)}let xe=f(U*q),Se=f(M*X),Me=f(G*P*Ee),me=f($*J),ze=f((U+M)*(q+X)-xe-Se),_t=me-Me,Ln=me+Me,Dn=f(Se-T*xe),up=f(ze*_t),fp=f(Ln*Dn),hp=f(ze*Dn),dp=f(_t*Ln);return new w(up,fp,dp,hp)}subtract(_){return this.add(_.negate())}wNAF(_){return R.wNAFCached(this,_,w.normalizeZ)}multiply(_){let T=_;Ge("scalar",T,Ye,n);let{p:P,f:U}=this.wNAF(T);return w.normalizeZ([P,U])[0]}multiplyUnsafe(_){let T=_;return Ge("scalar",T,ct,n),T===ct?A:this.equals(A)||T===Ye?this:this.equals(E)?this.wNAF(T).p:R.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(_){return y(this,_)}clearCofactor(){let{h:_}=e;return _===Ye?this:this.multiplyUnsafe(_)}static fromHex(_,T=!1){let{d:P,a:U}=e,M=t.BYTES;_=le("pointHex",_,M),at("zip215",T);let $=_.slice(),G=_[M-1];$[M-1]=G&-129;let q=Jt($),X=T?u:t.ORDER;Ge("pointHex.y",q,ct,X);let J=f(q*q),Ee=f(J-Ye),xe=f(P*J-U),{isValid:Se,value:Me}=d(Ee,xe);if(!Se)throw new Error("Point.fromHex: invalid y coordinate");let me=(Me&Ye)===Ye,ze=(G&128)!==0;if(!T&&Me===ct&&ze)throw new Error("Point.fromHex: x=0 and x_0=1");return ze!==me&&(Me=f(-Me)),w.fromAffine({x:Me,y:q})}static fromPrivateKey(_){return N(_).point}toRawBytes(){let{x:_,y:T}=this.toAffine(),P=vr(T,t.BYTES);return P[P.length-1]|=_&Ye?128:0,P}toHex(){return Bt(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Ye,f(e.Gx*e.Gy)),w.ZERO=new w(ct,Ye,Ye,ct);let{BASE:E,ZERO:A}=w,R=qo(w,a*8);function v(S){return Z(S,n)}function I(S){return v(Jt(S))}function N(S){let _=a;S=le("private key",S,_);let T=le("hashed private key",s(S),2*_),P=h(T.slice(0,_)),U=T.slice(_,2*_),M=I(P),$=E.multiply(M),G=$.toRawBytes();return{head:P,prefix:U,scalar:M,point:$,pointBytes:G}}function ee(S){return N(S).pointBytes}function H(S=new Uint8Array,..._){let T=kt(..._);return I(s(p(T,le("context",S),!!o)))}function K(S,_,T={}){S=le("message",S),o&&(S=o(S));let{prefix:P,scalar:U,pointBytes:M}=N(_),$=H(T.context,P,S),G=E.multiply($).toRawBytes(),q=H(T.context,G,M,S),X=v($+q*U);Ge("signature.s",X,ct,n);let J=kt(G,vr(X,t.BYTES));return le("result",J,a*2)}let O=_g;function B(S,_,T,P=O){let{context:U,zip215:M}=P,$=t.BYTES;S=le("signature",S,2*$),_=le("message",_),M!==void 0&&at("zip215",M),o&&(_=o(_));let G=Jt(S.slice($,2*$)),q,X,J;try{q=w.fromHex(T,M),X=w.fromHex(S.slice(0,$),M),J=E.multiplyUnsafe(G)}catch{return!1}if(!M&&q.isSmallOrder())return!1;let Ee=H(U,X.toRawBytes(),q.toRawBytes(),_);return X.add(q.multiplyUnsafe(Ee)).subtract(J).clearCofactor().equals(w.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:K,verify:B,ExtendedPoint:w,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,_=w.BASE){return _._setWindowSize(S),_.multiply(BigInt(3)),_}}}}var Xa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Zu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),gx=BigInt(0),Sg=BigInt(1),Qu=BigInt(2),yx=BigInt(3),Rg=BigInt(5),Ig=BigInt(8);function Tg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Xa,a=r*r%s*r%s,c=ne(a,Qu,s)*a%s,u=ne(c,Sg,s)*r%s,f=ne(u,Rg,s)*u%s,l=ne(f,e,s)*f%s,d=ne(l,t,s)*l%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,m=ne(p,o,s)*h%s,g=ne(m,e,s)*f%s;return{pow_p_5_8:ne(g,Qu,s)*r%s,b2:a}}function Bg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Cg(r,e){let t=Xa,n=Z(e*e*e,t),o=Z(n*n*e,t),s=Tg(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,u=Z(i*Zu,t),f=a===r,l=a===Z(-r,t),d=a===Z(-r*Zu,t);return f&&(i=c),(l||d)&&(i=u),Gu(i,t)&&(i=Z(-i,t)),{isValid:f||l,value:i}}var kg=tr(Xa,void 0,!0),Ng={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:kg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ig,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Vn,randomBytes:Jr,adjustScalarBytes:Bg,uvRatio:Cg},rn=Xu(Ng);var nn=32,Nt=64,Yo=32;function Ju(){let r=rn.utils.randomPrivateKey(),e=rn.getPublicKey(r);return{privateKey:nf(r,e),publicKey:e}}function ef(r){if(r.length!==Yo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=rn.getPublicKey(e);return{privateKey:nf(e,t),publicKey:t}}function tf(r,e){let t=r.subarray(0,Yo);return rn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function rf(r,e,t){return rn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function nf(r,e){let t=new Uint8Array(Nt);for(let n=0;n<Yo;n++)t[n]=r[n],t[Yo+n]=e[n];return t}var Fe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Za={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function of(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Fe.get();t*=8;async function c(l,d){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof d=="string"&&(d=L(d));let g;if(d.length===0){g=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,w,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,g,l);return Ie([h,m.iv,new Uint8Array(y)])}async function u(l,d){let h=l.subarray(0,s),p=l.subarray(s,s+n),m=l.subarray(s+n),g={name:e,iv:p};typeof d=="string"&&(d=L(d));let y;if(d.length===0)try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,E,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",Za,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,E,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,y,m);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function on(r,e){let n=await of().encrypt(r,e);return Mn.encode(n)}var Pg=Math.pow(2,7),Og=Math.pow(2,14),Ug=Math.pow(2,21),Qa=Math.pow(2,28),Ja=Math.pow(2,35),ec=Math.pow(2,42),tc=Math.pow(2,49),j=128,Le=127;function de(r){if(r<Pg)return 1;if(r<Og)return 2;if(r<Ug)return 3;if(r<Qa)return 4;if(r<Ja)return 5;if(r<ec)return 6;if(r<tc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function rc(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Mg(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function nc(r,e){let t=r[e],n=0;if(n+=t&Le,t<j||(t=r[e+1],n+=(t&Le)<<7,t<j)||(t=r[e+2],n+=(t&Le)<<14,t<j)||(t=r[e+3],n+=(t&Le)<<21,t<j)||(t=r[e+4],n+=(t&Le)*Qa,t<j)||(t=r[e+5],n+=(t&Le)*Ja,t<j)||(t=r[e+6],n+=(t&Le)*ec,t<j)||(t=r[e+7],n+=(t&Le)*tc,t<j))return n;throw new RangeError("Could not decode varint")}function Fg(r,e){let t=r.get(e),n=0;if(n+=t&Le,t<j||(t=r.get(e+1),n+=(t&Le)<<7,t<j)||(t=r.get(e+2),n+=(t&Le)<<14,t<j)||(t=r.get(e+3),n+=(t&Le)<<21,t<j)||(t=r.get(e+4),n+=(t&Le)*Qa,t<j)||(t=r.get(e+5),n+=(t&Le)*Ja,t<j)||(t=r.get(e+6),n+=(t&Le)*ec,t<j)||(t=r.get(e+7),n+=(t&Le)*tc,t<j))return n;throw new RangeError("Could not decode varint")}function De(r,e,t=0){return e==null&&(e=Ne(de(r))),e instanceof Uint8Array?rc(r,e,t):Mg(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?nc(r,e):Fg(r,e)}var oc=new Float32Array([-0]),rr=new Uint8Array(oc.buffer);function sf(r,e,t){oc[0]=r,e[t]=rr[0],e[t+1]=rr[1],e[t+2]=rr[2],e[t+3]=rr[3]}function af(r,e){return rr[0]=r[e],rr[1]=r[e+1],rr[2]=r[e+2],rr[3]=r[e+3],oc[0]}var sc=new Float64Array([-0]),Pe=new Uint8Array(sc.buffer);function cf(r,e,t){sc[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function lf(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],sc[0]}var Vg=BigInt(Number.MAX_SAFE_INTEGER),Kg=BigInt(Number.MIN_SAFE_INTEGER),Xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Rr;if(e<Vg&&e>Kg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>uf&&(o=0n,++n>uf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Rr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Rr}},Rr=new Xe(0,0);Rr.toBigInt=function(){return 0n};Rr.zzEncode=Rr.zzDecode=function(){return this};Rr.length=function(){return 1};var uf=4294967296n;function ff(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function hf(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ic(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function jo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ac=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ut(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ut(this,4);return jo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return jo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=af(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=lf(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return hf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ut(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ut(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ut(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ut(this,8);let e=jo(this.buf,this.pos+=4),t=jo(this.buf,this.pos+=4);return new Xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=nc(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function cc(r){return new ac(r instanceof Uint8Array?r:r.subarray())}function Ve(r,e,t){let n=cc(r);return e.decode(n,void 0,t)}function lc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ne(i);o+i>e&&(n=Ne(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Ir=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function uc(){}var hc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Hg=lc();function $g(r){return globalThis.Buffer!=null?Ne(r):Hg(r)}var zn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ir(uc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ir(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new dc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Wo,10,Xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Xe.fromBigInt(e);return this._push(Wo,t.length(),t)}uint64Number(e){return this._push(rc,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Xe.fromBigInt(e).zzEncode();return this._push(Wo,t.length(),t)}sint64Number(e){let t=Xe.fromNumber(e).zzEncode();return this._push(Wo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fc,1,e?1:0)}fixed32(e){return this._push(qn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Xe.fromBigInt(e);return this._push(qn,4,t.lo)._push(qn,4,t.hi)}fixed64Number(e){let t=Xe.fromNumber(e);return this._push(qn,4,t.lo)._push(qn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(sf,4,e)}double(e){return this._push(cf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fc,1,0):this.uint32(t)._push(zg,t,e)}string(e){let t=ff(e);return t!==0?this.uint32(t)._push(ic,t,e):this._push(fc,1,0)}fork(){return this.states=new hc(this),this.head=this.tail=new Ir(uc,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 Ir(uc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=$g(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function fc(r,e,t){e[t]=r&255}function qg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var dc=class extends Ir{next;constructor(e,t){super(qg,e,t),this.next=void 0}};function Wo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function qn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function zg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(zn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Gg,e,r),this},zn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Yg,e,r),this});function Gg(r,e,t){e.set(r,t)}function Yg(r,e,t){r.length<40?ic(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function pc(){return new zn}function Ke(r,e){let t=pc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var sn;(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"})(sn||(sn={}));function Xo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function mc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Xo("enum",sn.VARINT,t,n)}function He(r,e){return Xo("message",sn.LENGTH_DELIMITED,r,e)}var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(oe||(oe={}));var gc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(gc||(gc={}));(function(r){r.codec=()=>mc(gc)})(oe||(oe={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(yt||(yt={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(wt||(wt={}));var Gn=class{_key;constructor(e){this._key=an(e,nn)}verify(e,t){return rf(this._key,t,e)}marshal(){return this._key}get bytes(){return yt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}},Tr=class{_key;_publicKey;constructor(e,t){this._key=an(e,Nt),this._publicKey=an(t,nn)}sign(e){return tf(this._key,e)}get public(){return new Gn(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return tt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=It.digest(this.public.bytes);return ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function jg(r){if(r.length>Nt){r=an(r,Nt+nn);let n=r.subarray(0,Nt),o=r.subarray(Nt,r.length);return new Tr(n,o)}r=an(r,Nt);let e=r.subarray(0,Nt),t=r.subarray(nn);return new Tr(e,t)}function Wg(r){return r=an(r,nn),new Gn(r)}async function Xg(){let{privateKey:r,publicKey:e}=Ju();return new Tr(r,e)}async function pf(r){let{privateKey:e,publicKey:t}=ef(r);return new Tr(e,t)}function an(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new x(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function V(r,e="utf8"){let t=Uo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ic={};ve(Ic,{MAX_RSA_KEY_SIZE:()=>oo,RsaPrivateKey:()=>hn,RsaPublicKey:()=>no,fromJwk:()=>_0,generateKeyPair:()=>A0,unmarshalRsaPrivateKey:()=>Sc,unmarshalRsaPublicKey:()=>v0});function rt(r){if(isNaN(r)||r<=0)throw new x("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Jr(r)}var ir={};ve(ir,{exportToPem:()=>y0,importFromPem:()=>w0,jwkToPkcs1:()=>d0,jwkToPkix:()=>m0,pkcs1ToJwk:()=>h0,pkixToJwk:()=>p0});var Qo=class extends Zr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Mo(e);let n=Wt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Xr(this),this.iHash.update(e),this}digestInto(e){Xr(this),Wr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Yn=(r,e,t)=>new Qo(r,e).update(t).digest();Yn.create=(r,e)=>new Qo(r,e);function Zg(r,e,t,n){Mo(r);let o=Mu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(jr(s),jr(i),jr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wt(e),u=Wt(t),f=new Uint8Array(i),l=Yn.create(r,c),d=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:d}}function Qg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function wc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Zg(r,e,t,n),f,l=new Uint8Array(4),d=Qr(l),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<s;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);d.setInt32(0,p,!1),(f=u._cloneInto(f)).update(l).digestInto(h),g.set(h.subarray(0,g.length)),await Ou(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let y=0;y<g.length;y++)g[y]^=h[y]})}return Qg(c,u,a,f,h)}var z=gr(mf());function Br(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function nr(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function ts(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Ec(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Br(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Br(s,8)-n}function gf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=nr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=nr(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function yf(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function je(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var S1=Math.log(2);function rs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function xc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ut(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Wn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xc(this.items)}},jn=[new Uint8Array([1])],wf="0123456789";var un="",ht=new ArrayBuffer(0),vc=new Uint8Array(0),Xn="EndOfContent",Ef="OCTET STRING",xf="BIT STRING";function Mt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?z.BufferSourceConverter.toUint8Array(s.valueHex):vc}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(!Ut(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",ht)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:z.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Dt=class{constructor({blockLength:e=0,error:t=un,warnings:n=[],valueBeforeDecode:o=vc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=z.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:z.Convert.ToHex(this.valueBeforeDecodeView)}}};Dt.NAME="baseBlock";var Oe=class extends Dt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Oe.NAME="valueBlock";var ns=class extends Mt(Dt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?z.BufferSourceConverter.toUint8Array(e.valueHex):vc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ht}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=nr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Br(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ns.NAME="identificationBlock";var os=class extends Dt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Br(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=nr(this.length,8);if(o.byteLength>127)return this.error="Too big length",ht;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};os.NAME="lengthBlock";var C={},Te=class extends Dt{constructor({name:e=un,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ns(o),this.lenBlock=new os(o),this.valueBlock=s?new s(o):new Oe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Wn;t||vf(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ht:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():z.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return yf(t,n)}};Te.NAME="BaseBlock";function vf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)vf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ss=class extends Te{constructor({value:e=un,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ss.NAME="BaseStringBlock";var is=class extends Mt(Oe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};is.NAME="PrimitiveValueBlock";var _f,as=class extends Te{constructor(e={}){super(e,is),this.idBlock.isConstructed=!1}};_f=as;C.Primitive=_f;as.NAME="PRIMITIVE";function a0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Vs(r,e=0,t=r.length){let n=e,o=new Te({},Oe),s=new Dt;if(!Ut(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Te;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=a0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function fn(r){if(!r.byteLength){let e=new Te({},Oe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Vs(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function c0(r,e){return r?1:e}var bt=class extends Oe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;c0(this.isIndefiniteForm,n)>0;){let i=Vs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Xn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Wn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ht:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};bt.NAME="ConstructedValueBlock";var Af,or=class extends Te{constructor(e={}){super(e,bt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var Kp=Object.create;var No=Object.defineProperty;var qp=Object.getOwnPropertyDescriptor;var zp=Object.getOwnPropertyNames;var Gp=Object.getPrototypeOf,Wp=Object.prototype.hasOwnProperty;var Qe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Re=(r,e)=>{for(var t in e)No(r,t,{get:e[t],enumerable:!0})},Nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zp(e))!Wp.call(r,o)&&o!==t&&No(r,o,{get:()=>e[o],enumerable:!(n=qp(e,o))||n.enumerable});return r};var sr=(r,e,t)=>(t=r!=null?Kp(Gp(r)):{},Nu(e||!r||!r.__esModule?No(t,"default",{value:r,enumerable:!0}):t,r)),jp=r=>Nu(No({},"__esModule",{value:!0}),r);var Mf=Qe(Yr=>{"use strict";var y0="[object ArrayBuffer]",Ct=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===y0}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},zc="string",w0=/^[0-9a-f]+$/i,b0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,x0=/^[a-zA-Z0-9-_]+$/,ls=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Ct.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Ze=class{static toString(e,t=!1){let n=Ct.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},us=class r{static isHex(e){return typeof e===zc&&w0.test(e)}static isBase64(e){return typeof e===zc&&b0.test(e)}static isBase64Url(e){return typeof e===zc&&x0.test(e)}static ToString(e,t="utf8"){let n=Ct.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Ze.toString(n,!0);case"utf16":case"utf16be":return Ze.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Ze.fromString(e,!0);case"utf16":case"utf16be":return Ze.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Ct.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return ls.fromString(e);case"utf16":case"utf16be":return Ze.fromString(e);case"utf16le":case"usc2":return Ze.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return ls.toString(e);case"utf16":case"utf16be":return Ze.toString(e);case"utf16le":case"usc2":return Ze.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Ct.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Ct.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Ze.toString(e,t)}static FromUtf16String(e,t=!1){return Ze.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};us.DEFAULT_UTF8_ENCODING="utf8";function v0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function E0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function A0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Yr.BufferSourceConverter=Ct;Yr.Convert=us;Yr.assign=v0;Yr.combine=E0;Yr.isEqual=A0});var gd=Qe(lo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),lo.ip2long=i,lo.long2ip=a,lo.Netmask=r}).call(lo)});var bd=Qe((iS,Cl)=>{"use strict";var Iy=Object.prototype.hasOwnProperty,Ve="~";function uo(){}Object.create&&(uo.prototype=Object.create(null),new uo().__proto__||(Ve=!1));function Cy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function wd(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Cy(t,n||r,o),i=Ve?Ve+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function di(r,e){--r._eventsCount===0?r._events=new uo:delete r._events[e]}function Ne(){this._events=new uo,this._eventsCount=0}Ne.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Iy.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ne.prototype.listeners=function(e){var t=Ve?Ve+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ne.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ne.prototype.emit=function(e,t,n,o,s,i){var a=Ve?Ve+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Ne.prototype.on=function(e,t,n){return wd(this,e,t,n,!1)};Ne.prototype.once=function(e,t,n){return wd(this,e,t,n,!0)};Ne.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return di(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&di(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:di(this,s)}return this};Ne.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&di(this,t)):(this._events=new uo,this._eventsCount=0),this};Ne.prototype.off=Ne.prototype.removeListener;Ne.prototype.addListener=Ne.prototype.on;Ne.prefixed=Ve;Ne.EventEmitter=Ne;typeof Cl<"u"&&(Cl.exports=Ne)});var Sd=Qe((CS,Ad)=>{Ad.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Cd=Qe((WS,Id)=>{"use strict";Id.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Dd=Qe((Pd,Rd)=>{"use strict";var yi=Cd(),{hasOwnProperty:Ld}=Object.prototype,{propertyIsEnumerable:Ry}=Object,dn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Dy=Pd,Td={concatArrays:!1,ignoreUndefined:!1},wi=r=>{let e=[];for(let t in r)Ld.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ry.call(r,n)&&e.push(n)}return e};function pn(r){return Array.isArray(r)?My(r):yi(r)?Uy(r):r}function My(r){let e=r.slice(0,0);return wi(r).forEach(t=>{dn(e,t,pn(r[t]))}),e}function Uy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return wi(r).forEach(t=>{dn(e,t,pn(r[t]))}),e}var Nd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?dn(r,o,Ml(r[o],e[o],n)):dn(r,o,pn(e[o])))}),r),Oy=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Ld.call(s,a)&&(i.push(String(a)),s===r?dn(n,o++,s[a]):dn(n,o++,pn(s[a])));n=Nd(n,s,wi(s).filter(a=>!i.includes(a)),t)}),n};function Ml(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Oy(r,e,t):!yi(e)||!yi(r)?pn(e):Nd(r,e,wi(e),t)}Rd.exports=function(...r){let e=Ml(pn(Td),this!==Dy&&this||{},Td),t={_:{}};for(let n of r)if(n!==void 0){if(!yi(n))throw new TypeError("`"+n+"` is not an Option Object");t=Ml(t,{_:n},e)}return t._}});var Fd=Qe((mo,_i)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,x=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,x),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,x),y^=b}return y^=h.length,y=i(y),y>>>0},t.x86.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,x=p,A=0,_=0,v=0,B=0,T=597399067,ee=2869860233,V=951274213,F=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,T),A=s(A,15),A=o(A,ee),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,_=o(_,ee),_=s(_,16),_=o(_,V),b^=_,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,V),v=s(v,17),v=o(v,F),w^=v,w=s(w,15),w+=x,w=o(w,5)+2530024501,B=o(B,F),B=s(B,18),B=o(B,T),x^=B,x=s(x,13),x+=y,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,F),B=s(B,18),B=o(B,T),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,V),v=s(v,17),v=o(v,F),w^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,ee),_=s(_,16),_=o(_,V),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,T),A=s(A,15),A=o(A,ee),y^=A}return y^=h.length,b^=h.length,w^=h.length,x^=h.length,y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,y=i(y),b=i(b),w=i(w),x=i(x),y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],x=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[v+14]],48));case 14:x=l(x,f([0,h[v+13]],40));case 13:x=l(x,f([0,h[v+12]],32));case 12:x=l(x,f([0,h[v+11]],24));case 11:x=l(x,f([0,h[v+10]],16));case 10:x=l(x,f([0,h[v+9]],8));case 9:x=l(x,[0,h[v+8]]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof mo<"u"?(typeof _i<"u"&&_i.exports&&(mo=_i.exports=t),mo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(mo)});var Hd=Qe((E8,Vd)=>{Vd.exports=Fd()});var xp=Qe((iB,bp)=>{function Je(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}bp.exports=Je;Je.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Je.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Je.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Je.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Je.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Je.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Je.prototype.start=Je.prototype.try;Je.prototype.errors=function(){return this._errors};Je.prototype.attempts=function(){return this._attempts};Je.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=t&&(e=o,t=i)}return e}});var vp=Qe(Cr=>{var Fw=xp();Cr.operation=function(r){var e=Cr.timeouts(r);return new Fw(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Cr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<e.retries;o++)n.push(this.createTimeout(o,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,e)),n.sort(function(s,i){return s-i}),n};Cr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Cr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var o=0;o<t.length;o++){var s=t[o],i=r[s];r[s]=function(c){var u=Cr.operation(e),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=e}}});var Ap=Qe((cB,Ep)=>{Ep.exports=vp()});var hb={};Re(hb,{createLibp2p:()=>fb});var Pu=Symbol.for("@libp2p/connection");var Na=Symbol.for("@libp2p/content-routing");var Pa=Symbol.for("@libp2p/peer-discovery");var Po=Symbol.for("@libp2p/peer-id");function Ro(r){return!!r?.[Po]}var Ra=Symbol.for("@libp2p/peer-routing");var Da="keep-alive";var xb=Symbol.for("@libp2p/transport");var Ot;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ot||(Ot={}));var bt=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Nr=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var D=class extends Error{constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Pr=class extends Error{constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Bn=class extends Error{constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Do=class extends Error{constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Mo=class extends Error{constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Uo=class extends Error{constructor(e="Not found"){super(e),this.name="NotFoundError"}},Oo=class extends Error{constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Rr=class extends Error{constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Fo=class extends Error{constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vo=class extends Error{constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},kn=class extends Error{constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Ho=class extends Error{constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Dr=class extends Error{constructor(e="Timed out"){super(e),this.name="TimeoutError"}},xt=class extends Error{constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Mr=class extends Error{constructor(e="Dial error"){super(e),this.name="DialError"}};var Ur=class extends Error{constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},$o=class extends Error{constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Ko=class extends Error{constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var oe=(r,...e)=>{try{[...e]}catch{}};var vt=class extends EventTarget{#e=new Map;constructor(){super(),oe(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function qo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ru(...r){let e=[];for(let t of r)qo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Du(...r){let e=[];for(let t of r)qo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var In=Symbol.for("@libp2p/service-capabilities"),Ma=Symbol.for("@libp2p/service-dependencies");var Ha={};Re(Ha,{base58btc:()=>W,base58flickr:()=>em});var Xb=new Uint8Array(0);function Mu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Et(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Uu(r){return new TextEncoder().encode(r)}function Ou(r){return new TextDecoder().decode(r)}function Zp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,x=new Uint8Array(w);y!==b;){for(var A=p[y],_=0,v=w-1;(A!==0||_<g)&&v!==-1;v--,_++)A+=256*x[v]>>>0,x[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=_,y++}for(var B=w-g;B!==w&&x[B]===0;)B++;for(var T=c.repeat(m);B<w;++B)T+=r.charAt(x[B]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<y)&&_!==-1;_--,A++)x+=a*w[_]>>>0,w[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),T=g;v!==b;)B[T++]=w[v++];return B}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Xp=Zp,Yp=Xp,Vu=Yp;var Ua=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Oa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Hu(this,e)}},Fa=class{decoders;constructor(e){this.decoders=e}or(e){return Hu(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Hu(r,e){return new Fa({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Va=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ua(e,t,n),this.decoder=new Oa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Or({name:r,prefix:e,encode:t,decode:n}){return new Va(r,e,t,n)}function Vt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Vu(t,r);return Or({prefix:e,name:r,encode:n,decode:s=>Et(o(s))})}function Jp(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Qp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Or({prefix:e,name:r,encode(o){return Qp(o,n,t)},decode(o){return Jp(o,n,t,r)}})}var W=Vt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),em=Vt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $a={};Re($a,{base32:()=>ze,base32hex:()=>om,base32hexpad:()=>im,base32hexpadupper:()=>am,base32hexupper:()=>sm,base32pad:()=>rm,base32padupper:()=>nm,base32upper:()=>tm,base32z:()=>cm});var ze=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tm=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rm=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nm=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),om=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sm=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),im=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),am=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cm=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var lm=qu,$u=128,um=127,fm=~um,hm=Math.pow(2,31);function qu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hm;)e[t++]=r&255|$u,r/=128;for(;r&fm;)e[t++]=r&255|$u,r>>>=7;return e[t]=r|0,qu.bytes=t-n+1,e}var dm=Ka,pm=128,Ku=127;function Ka(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ka.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ku)<<o:(i&Ku)*Math.pow(2,o),o+=7}while(i>=pm);return Ka.bytes=s-n,t}var mm=Math.pow(2,7),gm=Math.pow(2,14),ym=Math.pow(2,21),wm=Math.pow(2,28),bm=Math.pow(2,35),xm=Math.pow(2,42),vm=Math.pow(2,49),Em=Math.pow(2,56),Am=Math.pow(2,63),Sm=function(r){return r<mm?1:r<gm?2:r<ym?3:r<wm?4:r<bm?5:r<xm?6:r<vm?7:r<Em?8:r<Am?9:10},_m={encode:lm,decode:dm,encodingLength:Sm},Bm=_m,Cn=Bm;function Tn(r,e=0){return[Cn.decode(r,e),Cn.decode.bytes]}function Fr(r,e,t=0){return Cn.encode(r,e,t),e}function Vr(r){return Cn.encodingLength(r)}function et(r,e){let t=e.byteLength,n=Vr(r),o=n+Vr(t),s=new Uint8Array(o+t);return Fr(r,s,0),Fr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function tt(r){let e=Et(r),[t,n]=Tn(e),[o,s]=Tn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hr(t,o,i,e)}function zu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Mu(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Gu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Im(t,qa(r),e??W.encoder);default:return Cm(t,qa(r),e??ze.encoder)}}var Wu=new WeakMap;function qa(r){let e=Wu.get(r);if(e==null){let t=new Map;return Wu.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ln)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Tm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=et(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&zu(e.multihash,n.multihash)}toString(e){return Gu(this,e)}toJSON(){return{"/":Gu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ju(n,o,s.bytes))}else if(t[Lm]===!0){let{version:n,multihash:o,code:s}=t,i=tt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ln)throw new Error(`Version 0 CID must use dag-pb (code: ${Ln}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ju(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ln,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Et(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Hr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=Tn(e.subarray(t));return t+=d,l},o=n(),s=Ln;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=km(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qa(s).set(n,e),s}};function km(r,e){switch(r[0]){case"Q":{let t=e??W;return[W.prefix,t.decode(`${W.prefix}${r}`)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Im(r,e,t){let{prefix:n}=t;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Cm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ln=112,Tm=18;function ju(r,e,t){let n=Vr(r),o=n+Vr(e),s=new Uint8Array(o+t.byteLength);return Fr(r,s,0),Fr(e,s,n),s.set(t,o),s}var Lm=Symbol.for("@ipld/js-cid/CID");var za={};Re(za,{identity:()=>St});var Zu=0,Nm="identity",Xu=Et;function Pm(r){return et(Zu,Xu(r))}var St={code:Zu,name:Nm,encode:Xu,digest:Pm};function ie(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Yu(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Rm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function $r(r,...e){if(!Rm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Ju(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yu(r.outputLen),Yu(r.blockLen)}function Kr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Qu(r,e){$r(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Go=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),rt=(r,e)=>r<<32-e|r>>>e;var yx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Nn(r){return typeof r=="string"&&(r=ef(r)),$r(r),r}function Ga(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$r(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var qr=class{clone(){return this._cloneInto()}},wx={}.toString;function Wo(r){let e=n=>r().update(Nn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function zr(r=32){if(ir&&typeof ir.getRandomValues=="function")return ir.getRandomValues(new Uint8Array(r));if(ir&&typeof ir.randomBytes=="function")return ir.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Dm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var tf=(r,e,t)=>r&e^~r&t,rf=(r,e,t)=>r&e^r&t^e&t,Gr=class extends qr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){Kr(this);let{view:t,buffer:n,blockLen:o}=this;e=Nn(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Go(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Kr(this),Qu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;Dm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Go(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var jo=BigInt(4294967295),Wa=BigInt(32);function nf(r,e=!1){return e?{h:Number(r&jo),l:Number(r>>Wa&jo)}:{h:Number(r>>Wa&jo)|0,l:Number(r&jo)|0}}function Mm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=nf(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Um=(r,e)=>BigInt(r>>>0)<<Wa|BigInt(e>>>0),Om=(r,e,t)=>r>>>t,Fm=(r,e,t)=>r<<32-t|e>>>t,Vm=(r,e,t)=>r>>>t|e<<32-t,Hm=(r,e,t)=>r<<32-t|e>>>t,$m=(r,e,t)=>r<<64-t|e>>>t-32,Km=(r,e,t)=>r>>>t-32|e<<64-t,qm=(r,e)=>e,zm=(r,e)=>r,Gm=(r,e,t)=>r<<t|e>>>32-t,Wm=(r,e,t)=>e<<t|r>>>32-t,jm=(r,e,t)=>e<<t-32|r>>>64-t,Zm=(r,e,t)=>r<<t-32|e>>>64-t;function Xm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ym=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Jm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Qm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),eg=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,tg=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),rg=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var ng={fromBig:nf,split:Mm,toBig:Um,shrSH:Om,shrSL:Fm,rotrSH:Vm,rotrSL:Hm,rotrBH:$m,rotrBL:Km,rotr32H:qm,rotr32L:zm,rotlSH:Gm,rotlSL:Wm,rotlBH:jm,rotlBL:Zm,add:Xm,add3L:Ym,add3H:Jm,add4L:Qm,add4H:eg,add5H:rg,add5L:tg},O=ng;var[og,sg]=O.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Ht=new Uint32Array(80),$t=new Uint32Array(80),ja=class extends Gr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)Ht[w]=e.getUint32(t),$t[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=Ht[w-15]|0,A=$t[w-15]|0,_=O.rotrSH(x,A,1)^O.rotrSH(x,A,8)^O.shrSH(x,A,7),v=O.rotrSL(x,A,1)^O.rotrSL(x,A,8)^O.shrSL(x,A,7),B=Ht[w-2]|0,T=$t[w-2]|0,ee=O.rotrSH(B,T,19)^O.rotrBH(B,T,61)^O.shrSH(B,T,6),V=O.rotrSL(B,T,19)^O.rotrBL(B,T,61)^O.shrSL(B,T,6),F=O.add4L(v,V,$t[w-7],$t[w-16]),R=O.add4H(F,_,ee,Ht[w-7],Ht[w-16]);Ht[w]=R|0,$t[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let x=O.rotrSH(l,d,14)^O.rotrSH(l,d,18)^O.rotrBH(l,d,41),A=O.rotrSL(l,d,14)^O.rotrSL(l,d,18)^O.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=O.add5L(b,A,v,sg[w],$t[w]),T=O.add5H(B,y,x,_,og[w],Ht[w]),ee=B|0,V=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),F=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),R=n&s^n&a^s&a,I=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=O.add(u|0,f|0,T|0,ee|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=O.add3L(ee,F,I);n=O.add3H(L,T,V,R),o=L|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=O.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=O.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=O.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=O.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){Ht.fill(0),$t.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 of=Wo(()=>new ja);var Xo={};Re(Xo,{aInRange:()=>$e,abool:()=>nt,abytes:()=>Wr,bitGet:()=>fg,bitLen:()=>Qa,bitMask:()=>Rn,bitSet:()=>hg,bytesToHex:()=>Bt,bytesToNumberBE:()=>kt,bytesToNumberLE:()=>qt,concatBytes:()=>It,createHmacDrbg:()=>ec,ensureBytes:()=>ae,equalBytes:()=>lg,hexToBytes:()=>cr,hexToNumber:()=>Ja,inRange:()=>Pn,isBytes:()=>Kt,memoized:()=>ur,notImplemented:()=>pg,numberToBytesBE:()=>zt,numberToBytesLE:()=>lr,numberToHexUnpadded:()=>ar,numberToVarBytesBE:()=>cg,utf8ToBytes:()=>ug,validateObject:()=>ut});var Ya=BigInt(0),Zo=BigInt(1),ig=BigInt(2);function Kt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wr(r){if(!Kt(r))throw new Error("Uint8Array expected")}function nt(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var ag=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){Wr(r);let e="";for(let t=0;t<r.length;t++)e+=ag[r[t]];return e}function ar(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ja(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _t={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function sf(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t._A&&r<=_t._F)return r-(_t._A-10);if(r>=_t._a&&r<=_t._f)return r-(_t._a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=sf(r.charCodeAt(s)),a=sf(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 kt(r){return Ja(Bt(r))}function qt(r){return Wr(r),Ja(Bt(Uint8Array.from(r).reverse()))}function zt(r,e){return cr(r.toString(16).padStart(e*2,"0"))}function lr(r,e){return zt(r,e).reverse()}function cg(r){return cr(ar(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=cr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Kt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function It(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Wr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function lg(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ug(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Za=r=>typeof r=="bigint"&&Ya<=r;function Pn(r,e,t){return Za(r)&&Za(e)&&Za(t)&&e<=r&&r<t}function $e(r,e,t,n){if(!Pn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function Qa(r){let e;for(e=0;r>Ya;r>>=Zo,e+=1);return e}function fg(r,e){return r>>BigInt(e)&Zo}function hg(r,e,t){return r|(t?Zo:Ya)<<BigInt(e)}var Rn=r=>(ig<<BigInt(r-1))-Zo,Xa=r=>new Uint8Array(r),af=r=>Uint8Array.from(r);function ec(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Xa(r),o=Xa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Xa())=>{o=a(af([0]),l),n=a(),l.length!==0&&(o=a(af([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<e;){n=a();let h=n.slice();d.push(h),l+=n.length}return It(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var dg={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"||Kt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ut(r,e,t={}){let n=(o,s,i)=>{let a=dg[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var pg=()=>{throw new Error("not implemented")};function ur(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var me=BigInt(0),te=BigInt(1),fr=BigInt(2),mg=BigInt(3),tc=BigInt(4),cf=BigInt(5),lf=BigInt(8),gg=BigInt(9),yg=BigInt(16);function Y(r,e){let t=r%e;return t>=me?t:e+t}function wg(r,e,t){if(t<=me||e<me)throw new Error("Expected power/modulo > 0");if(t===te)return me;let n=te;for(;e>me;)e&te&&(n=n*r%t),r=r*r%t,e>>=te;return n}function re(r,e,t){let n=r;for(;e-- >me;)n*=n,n%=t;return n}function Yo(r,e){if(r===me||e<=me)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Y(r,e),n=e,o=me,s=te,i=te,a=me;for(;t!==me;){let u=n/t,f=n%t,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==te)throw new Error("invert: does not exist");return Y(o,e)}function bg(r){let e=(r-te)/fr,t,n,o;for(t=r-te,n=0;t%fr===me;t/=fr,n++);for(o=fr;o<r&&wg(o,e,r)!==r-te;o++);if(n===1){let i=(r+te)/tc;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+te)/fr;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,te<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function xg(r){if(r%tc===mg){let e=(r+te)/tc;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%lf===cf){let e=(r-cf)/lf;return function(n,o){let s=n.mul(o,fr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,fr),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%yg,bg(r)}var uf=(r,e)=>(Y(r,e)&te)===te,vg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=vg.reduce((n,o)=>(n[o]="function",n),e);return ut(r,t)}function Eg(r,e,t){if(t<me)throw new Error("Expected power > 0");if(t===me)return r.ONE;if(t===te)return e;let n=r.ONE,o=e;for(;t>me;)t&te&&(n=r.mul(n,o)),o=r.sqr(o),t>>=te;return n}function Ag(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function nc(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Gt(r,e,t=!1,n={}){if(r<=me)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=nc(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=xg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Rn(o),ZERO:me,ONE:te,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return me<=c&&c<r},is0:c=>c===me,isOdd:c=>(c&te)===te,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>Eg(a,c,u),div:(c,u)=>Y(c*Yo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Ag(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?lr(c,s):zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?qt(c):kt(c)}});return Object.freeze(a)}function ff(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function oc(r){let e=ff(r);return e+Math.ceil(e/2)}function hf(r,e,t=!1){let n=r.length,o=ff(e),s=oc(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?kt(r):qt(r),a=Y(i,e-te)+te;return t?lr(a,o):zt(a,o)}var _g=BigInt(0),sc=BigInt(1),ic=new WeakMap,df=new WeakMap;function Jo(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>_g;)i&sc&&(a=a.add(c)),c=c.double(),i>>=sc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=sc);let b=g,w=g+Math.abs(y)-1,x=m%2!==0,A=y<0;y===0?l=l.add(t(x,i[b])):f=f.add(t(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=df.get(s)||1,u=ic.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&ic.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),df.set(s,i),ic.delete(s)}}}function Qo(r,e,t,n){if(!Array.isArray(t)||!Array.isArray(n)||n.length!==t.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!e.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),t.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Qa(BigInt(t.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((e.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(t[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function Dn(r){return rc(r.Fp),ut(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ot=BigInt(0),Ke=BigInt(1),es=BigInt(2),Bg=BigInt(8),kg={zip215:!0};function Ig(r){let e=Dn(r);return ut(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function pf(r){let e=Ig(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=es<<BigInt(a*8)-Ke,f=t.create,l=Gt(e.n,e.nBitLength),d=e.uvRatio||((S,E)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(E))}}catch{return{isValid:!1,value:ot}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,k)=>{if(nt("phflag",k),E.length||k)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){$e("coordinate "+S,E,ot,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=ur((S,E)=>{let{ex:k,ey:N,ez:M}=S,U=S.is0();E==null&&(E=U?Bg:t.inv(M));let $=f(k*E),z=f(N*E),K=f(M*E);if(U)return{x:ot,y:Ke};if(K!==Ke)throw new Error("invZ was invalid");return{x:$,y:z}}),b=ur(S=>{let{a:E,d:k}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:N,ey:M,ez:U,et:$}=S,z=f(N*N),K=f(M*M),X=f(U*U),Q=f(X*X),be=f(z*E),xe=f(X*f(be+K)),Ee=f(Q+f(k*f(z*K)));if(xe!==Ee)throw new Error("bad point: equation left != right (1)");let Pe=f(N*M),de=f(U*$);if(Pe!==de)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,k,N,M){this.ex=E,this.ey=k,this.ez=N,this.et=M,m("x",E),m("y",k),m("z",N),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");let{x:k,y:N}=E||{};return m("x",k),m("y",N),new w(k,N,Ke,f(k*N))}static normalizeZ(E){let k=t.invertBatch(E.map(N=>N.ez));return E.map((N,M)=>N.toAffine(k[M])).map(w.fromAffine)}static msm(E,k){return Qo(w,l,E,k)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:k,ey:N,ez:M}=this,{ex:U,ey:$,ez:z}=E,K=f(k*z),X=f(U*M),Q=f(N*z),be=f($*M);return K===X&&Q===be}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:k,ey:N,ez:M}=this,U=f(k*k),$=f(N*N),z=f(es*f(M*M)),K=f(E*U),X=k+N,Q=f(f(X*X)-U-$),be=K+$,xe=be-z,Ee=K-$,Pe=f(Q*xe),de=f(be*Ee),He=f(Q*Ee),wt=f(xe*be);return new w(Pe,de,wt,He)}add(E){g(E);let{a:k,d:N}=e,{ex:M,ey:U,ez:$,et:z}=this,{ex:K,ey:X,ez:Q,et:be}=E;if(k===BigInt(-1)){let _u=f((U-M)*(X+K)),Bu=f((U+M)*(X-K)),La=f(Bu-_u);if(La===ot)return this.double();let ku=f($*es*be),Iu=f(z*es*Q),Cu=Iu+ku,Tu=Bu+_u,Lu=Iu-ku,Fp=f(Cu*La),Vp=f(Tu*Lu),Hp=f(Cu*Lu),$p=f(La*Tu);return new w(Fp,Vp,$p,Hp)}let xe=f(M*K),Ee=f(U*X),Pe=f(z*N*be),de=f($*Q),He=f((M+U)*(K+X)-xe-Ee),wt=de-Pe,Sn=de+Pe,_n=f(Ee-k*xe),Dp=f(He*wt),Mp=f(Sn*_n),Up=f(He*_n),Op=f(wt*Sn);return new w(Dp,Mp,Op,Up)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){let k=E;$e("scalar",k,Ke,n);let{p:N,f:M}=this.wNAF(k);return w.normalizeZ([N,M])[0]}multiplyUnsafe(E){let k=E;return $e("scalar",k,ot,n),k===ot?A:this.equals(A)||k===Ke?this:this.equals(x)?this.wNAF(k).p:_.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return y(this,E)}clearCofactor(){let{h:E}=e;return E===Ke?this:this.multiplyUnsafe(E)}static fromHex(E,k=!1){let{d:N,a:M}=e,U=t.BYTES;E=ae("pointHex",E,U),nt("zip215",k);let $=E.slice(),z=E[U-1];$[U-1]=z&-129;let K=qt($),X=k?u:t.ORDER;$e("pointHex.y",K,ot,X);let Q=f(K*K),be=f(Q-Ke),xe=f(N*Q-M),{isValid:Ee,value:Pe}=d(be,xe);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let de=(Pe&Ke)===Ke,He=(z&128)!==0;if(!k&&Pe===ot&&He)throw new Error("Point.fromHex: x=0 and x_0=1");return He!==de&&(Pe=f(-Pe)),w.fromAffine({x:Pe,y:K})}static fromPrivateKey(E){return T(E).point}toRawBytes(){let{x:E,y:k}=this.toAffine(),N=lr(k,t.BYTES);return N[N.length-1]|=E&Ke?128:0,N}toHex(){return Bt(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Ke,f(e.Gx*e.Gy)),w.ZERO=new w(ot,Ke,Ke,ot);let{BASE:x,ZERO:A}=w,_=Jo(w,a*8);function v(S){return Y(S,n)}function B(S){return v(qt(S))}function T(S){let E=a;S=ae("private key",S,E);let k=ae("hashed private key",s(S),2*E),N=h(k.slice(0,E)),M=k.slice(E,2*E),U=B(N),$=x.multiply(U),z=$.toRawBytes();return{head:N,prefix:M,scalar:U,point:$,pointBytes:z}}function ee(S){return T(S).pointBytes}function V(S=new Uint8Array,...E){let k=It(...E);return B(s(p(k,ae("context",S),!!o)))}function F(S,E,k={}){S=ae("message",S),o&&(S=o(S));let{prefix:N,scalar:M,pointBytes:U}=T(E),$=V(k.context,N,S),z=x.multiply($).toRawBytes(),K=V(k.context,z,U,S),X=v($+K*M);$e("signature.s",X,ot,n);let Q=It(z,lr(X,t.BYTES));return ae("result",Q,a*2)}let R=kg;function I(S,E,k,N=R){let{context:M,zip215:U}=N,$=t.BYTES;S=ae("signature",S,2*$),E=ae("message",E),U!==void 0&&nt("zip215",U),o&&(E=o(E));let z=qt(S.slice($,2*$)),K,X,Q;try{K=w.fromHex(k,U),X=w.fromHex(S.slice(0,$),U),Q=x.multiplyUnsafe(z)}catch{return!1}if(!U&&K.isSmallOrder())return!1;let be=V(M,X.toRawBytes(),K.toRawBytes(),E);return X.add(K.multiplyUnsafe(be)).subtract(Q).clearCofactor().equals(w.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:F,verify:I,ExtendedPoint:w,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,E=w.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var ac=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),mf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Hx=BigInt(0),Cg=BigInt(1),gf=BigInt(2),$x=BigInt(3),Tg=BigInt(5),Lg=BigInt(8);function Ng(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=ac,a=r*r%s*r%s,c=re(a,gf,s)*a%s,u=re(c,Cg,s)*r%s,f=re(u,Tg,s)*u%s,l=re(f,e,s)*f%s,d=re(l,t,s)*l%s,h=re(d,n,s)*d%s,p=re(h,o,s)*h%s,m=re(p,o,s)*h%s,g=re(m,e,s)*f%s;return{pow_p_5_8:re(g,gf,s)*r%s,b2:a}}function Pg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Rg(r,e){let t=ac,n=Y(e*e*e,t),o=Y(n*n*e,t),s=Ng(r*o).pow_p_5_8,i=Y(r*n*s,t),a=Y(e*i*i,t),c=i,u=Y(i*mf,t),f=a===r,l=a===Y(-r,t),d=a===Y(-r*mf,t);return f&&(i=c),(l||d)&&(i=u),uf(i,t)&&(i=Y(-i,t)),{isValid:f||l,value:i}}var Dg=Gt(ac,void 0,!0),Mg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Lg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:of,randomBytes:zr,adjustScalarBytes:Pg,uvRatio:Rg},Mn=pf(Mg);var ts=32,rs=64,cc=32;function yf(){let r=Mn.utils.randomPrivateKey(),e=Mn.getPublicKey(r);return{privateKey:Ug(r,e),publicKey:e}}function wf(r,e){let t=r.subarray(0,cc);return Mn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function bf(r,e,t){return Mn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Ug(r,e){let t=new Uint8Array(rs);for(let n=0;n<cc;n++)t[n]=r[n],t[cc+n]=e[n];return t}var Un=class{type="Ed25519";raw;constructor(e){this.raw=os(e,ts)}toMultihash(){return St.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return bf(this.raw,t,e)}},ns=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=os(e,rs),this.publicKey=new Un(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return wf(this.raw,e)}};function lc(r){return r=os(r,ts),new Un(r)}async function vf(){let{privateKey:r,publicKey:e}=yf();return new ns(r,e)}function os(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new D(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function ce(r=0){return new Uint8Array(r)}function ke(r=0){return new Uint8Array(r)}var Og=Math.pow(2,7),Fg=Math.pow(2,14),Vg=Math.pow(2,21),uc=Math.pow(2,28),fc=Math.pow(2,35),hc=Math.pow(2,42),dc=Math.pow(2,49),j=128,Ie=127;function he(r){if(r<Og)return 1;if(r<Fg)return 2;if(r<Vg)return 3;if(r<uc)return 4;if(r<fc)return 5;if(r<hc)return 6;if(r<dc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pc(r,e,t=0){switch(he(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Hg(r,e,t=0){switch(he(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function mc(r,e){let t=r[e],n=0;if(n+=t&Ie,t<j||(t=r[e+1],n+=(t&Ie)<<7,t<j)||(t=r[e+2],n+=(t&Ie)<<14,t<j)||(t=r[e+3],n+=(t&Ie)<<21,t<j)||(t=r[e+4],n+=(t&Ie)*uc,t<j)||(t=r[e+5],n+=(t&Ie)*fc,t<j)||(t=r[e+6],n+=(t&Ie)*hc,t<j)||(t=r[e+7],n+=(t&Ie)*dc,t<j))return n;throw new RangeError("Could not decode varint")}function $g(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<j||(t=r.get(e+1),n+=(t&Ie)<<7,t<j)||(t=r.get(e+2),n+=(t&Ie)<<14,t<j)||(t=r.get(e+3),n+=(t&Ie)<<21,t<j)||(t=r.get(e+4),n+=(t&Ie)*uc,t<j)||(t=r.get(e+5),n+=(t&Ie)*fc,t<j)||(t=r.get(e+6),n+=(t&Ie)*hc,t<j)||(t=r.get(e+7),n+=(t&Ie)*dc,t<j))return n;throw new RangeError("Could not decode varint")}function Ce(r,e,t=0){return e==null&&(e=ke(he(r))),e instanceof Uint8Array?pc(r,e,t):Hg(r,e,t)}function st(r,e=0){return r instanceof Uint8Array?mc(r,e):$g(r,e)}var gc=new Float32Array([-0]),Wt=new Uint8Array(gc.buffer);function Ef(r,e,t){gc[0]=r,e[t]=Wt[0],e[t+1]=Wt[1],e[t+2]=Wt[2],e[t+3]=Wt[3]}function Af(r,e){return Wt[0]=r[e],Wt[1]=r[e+1],Wt[2]=r[e+2],Wt[3]=r[e+3],gc[0]}var yc=new Float64Array([-0]),Te=new Uint8Array(yc.buffer);function Sf(r,e,t){yc[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function _f(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],yc[0]}var Kg=BigInt(Number.MAX_SAFE_INTEGER),qg=BigInt(Number.MIN_SAFE_INTEGER),Ge=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return dr;if(e<Kg&&e>qg)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Bf&&(o=0n,++n>Bf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return dr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):dr}},dr=new Ge(0,0);dr.toBigInt=function(){return 0n};dr.zzEncode=dr.zzDecode=function(){return this};dr.length=function(){return 1};var Bf=4294967296n;function kf(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function If(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function wc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function it(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ss(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,it(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw it(this,4);return ss(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw it(this,4);return ss(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw it(this,4);let e=Af(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw it(this,4);let e=_f(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw it(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return If(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw it(this,e);this.pos+=e}else do if(this.pos>=this.len)throw it(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ge(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw it(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw it(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw it(this,8);let e=ss(this.buf,this.pos+=4),t=ss(this.buf,this.pos+=4);return new Ge(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=mc(this.buf,this.pos);return this.pos+=he(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function xc(r){return new bc(r instanceof Uint8Array?r:r.subarray())}function De(r,e,t){let n=xc(r);return e.decode(n,void 0,t)}var vc={};Re(vc,{base10:()=>zg});var zg=Vt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ec={};Re(Ec,{base16:()=>Gg,base16upper:()=>Wg});var Gg=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Wg=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ac={};Re(Ac,{base2:()=>jg});var jg=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Sc={};Re(Sc,{base256emoji:()=>Qg});var Tf=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}"),Zg=Tf.reduce((r,e,t)=>(r[t]=e,r),[]),Xg=Tf.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Yg(r){return r.reduce((e,t)=>(e+=Zg[t],e),"")}function Jg(r){let e=[];for(let t of r){let n=Xg[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Qg=Or({prefix:"\u{1F680}",name:"base256emoji",encode:Yg,decode:Jg});var _c={};Re(_c,{base36:()=>e0,base36upper:()=>t0});var e0=Vt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),t0=Vt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ic={};Re(Ic,{base64:()=>Bc,base64pad:()=>r0,base64url:()=>kc,base64urlpad:()=>n0});var Bc=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),r0=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),kc=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),n0=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Cc={};Re(Cc,{base8:()=>o0});var o0=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Tc={};Re(Tc,{identity:()=>s0});var s0=Or({prefix:"\0",name:"identity",encode:r=>Ou(r),decode:r=>Uu(r)});var E1=new TextEncoder,A1=new TextDecoder;var Pc={};Re(Pc,{sha256:()=>jr,sha512:()=>c0});function Nc({name:r,code:e,encode:t}){return new Lc(r,e,t)}var Lc=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?et(this.code,t):t.then(n=>et(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Nf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var jr=Nc({name:"sha2-256",code:18,encode:Nf("SHA-256")}),c0=Nc({name:"sha2-512",code:19,encode:Nf("SHA-512")});var On={...Tc,...Ac,...Cc,...vc,...Ec,...$a,..._c,...Ha,...Ic,...Sc},D1={...Pc,...za};function Rf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Pf=Rf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Rc=Rf("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ke(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),l0={utf8:Pf,"utf-8":Pf,hex:On.base16,latin1:Rc,ascii:Rc,binary:Rc,...On},is=l0;function P(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Dc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ke(i);o+i>e&&(n=ke(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var pr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Mc(){}var Oc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},u0=Dc();function f0(r){return globalThis.Buffer!=null?ke(r):u0(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new pr(Mc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Fc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(as,10,Ge.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ge.fromBigInt(e);return this._push(as,t.length(),t)}uint64Number(e){return this._push(pc,he(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ge.fromBigInt(e).zzEncode();return this._push(as,t.length(),t)}sint64Number(e){let t=Ge.fromNumber(e).zzEncode();return this._push(as,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Uc,1,e?1:0)}fixed32(e){return this._push(Fn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ge.fromBigInt(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64Number(e){let t=Ge.fromNumber(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ef,4,e)}double(e){return this._push(Sf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Uc,1,0):this.uint32(t)._push(d0,t,e)}string(e){let t=kf(e);return t!==0?this.uint32(t)._push(wc,t,e):this._push(Uc,1,0)}fork(){return this.states=new Oc(this),this.head=this.tail=new pr(Mc,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 pr(Mc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=f0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Uc(r,e,t){e[t]=r&255}function h0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Fc=class extends pr{next;constructor(e,t){super(h0,e,t),this.next=void 0}};function as(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Fn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function d0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(p0,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(m0,e,r),this});function p0(r,e,t){e.set(r,t)}function m0(r,e,t){r.length<40?wc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function Vc(){return new Vn}function Me(r,e){let t=Vc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Zr;(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"})(Zr||(Zr={}));function cs(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Hc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return cs("enum",Zr.VARINT,t,n)}function Ue(r,e){return cs("message",Zr.LENGTH_DELIMITED,r,e)}var mr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Hn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ge||(ge={}));var $c;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})($c||($c={}));(function(r){r.codec=()=>Hc($c)})(ge||(ge={}));var ht;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ge.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(ht||(ht={}));var Kc;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ge.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Kc||(Kc={}));var Jn={};Re(Jn,{MAX_RSA_KEY_SIZE:()=>Qs,generateRSAKeyPair:()=>el,jwkToJWKKeyPair:()=>Lh,jwkToPkcs1:()=>L0,jwkToPkix:()=>Jc,jwkToRSAPrivateKey:()=>Th,pkcs1ToJwk:()=>kh,pkcs1ToRSAPrivateKey:()=>Ch,pkixToJwk:()=>Ih,pkixToRSAPublicKey:()=>Qc});var g0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zt=new Uint32Array(64),qc=class extends Gr{constructor(){super(64,32,8,!1),this.A=jt[0]|0,this.B=jt[1]|0,this.C=jt[2]|0,this.D=jt[3]|0,this.E=jt[4]|0,this.F=jt[5]|0,this.G=jt[6]|0,this.H=jt[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)Zt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Zt[l-15],h=Zt[l-2],p=rt(d,7)^rt(d,18)^d>>>3,m=rt(h,17)^rt(h,19)^h>>>10;Zt[l]=m+Zt[l-7]+p+Zt[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=rt(a,6)^rt(a,11)^rt(a,25),h=f+d+tf(a,c,u)+g0[l]+Zt[l]|0,m=(rt(n,2)^rt(n,13)^rt(n,22))+rf(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(){Zt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Xr=Wo(()=>new qc);var q=sr(Mf());function gr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Xt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function fs(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Gc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=gr(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,gr(s,8)-n}function Uf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Xt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Xt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Of(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function qe(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var gv=Math.log(2);function hs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Wc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Pt(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Kn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wc(this.items)}},$n=[new Uint8Array([1])],Ff="0123456789";var tn="",at=new ArrayBuffer(0),jc=new Uint8Array(0),qn="EndOfContent",Hf="OCTET STRING",$f="BIT STRING";function Rt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):jc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Pt(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",at)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Tt=class{constructor({blockLength:e=0,error:t=tn,warnings:n=[],valueBeforeDecode:o=jc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Tt.NAME="baseBlock";var Le=class extends Tt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Le.NAME="valueBlock";var ds=class extends Rt(Tt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):jc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",at}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Xt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=gr(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ds.NAME="identificationBlock";var ps=class extends Tt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=gr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Xt(this.length,8);if(o.byteLength>127)return this.error="Too big length",at;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ps.NAME="lengthBlock";var C={},Ae=class extends Tt{constructor({name:e=tn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ds(o),this.lenBlock=new ps(o),this.valueBlock=s?new s(o):new Le(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Kn;t||Kf(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?at:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Of(t,n)}};Ae.NAME="BaseBlock";function Kf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Kf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ms=class extends Ae{constructor({value:e=tn,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ms.NAME="BaseStringBlock";var gs=class extends Rt(Le){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};gs.NAME="PrimitiveValueBlock";var qf,ys=class extends Ae{constructor(e={}){super(e,gs),this.idBlock.isConstructed=!1}};qf=ys;C.Primitive=qf;ys.NAME="PRIMITIVE";function _0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ys(r,e=0,t=r.length){let n=e,o=new Ae({},Le),s=new Tt;if(!Pt(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ae;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=_0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Zc(r){if(!r.byteLength){let e=new Ae({},Le);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ys(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function B0(r,e){return r?1:e}var dt=class extends Le{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;B0(this.isIndefiniteForm,n)>0;){let i=Ys(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===qn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===qn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Kn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?at:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};dt.NAME="ConstructedValueBlock";var zf,Yt=class extends Ae{constructor(e={}){super(e,dt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
3
3
|
`).map(o=>` ${o}`).join(`
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
6
|
-
`)}`:`${t} :`}};Af=or;C.Constructed=Af;or.NAME="CONSTRUCTED";var cs=class extends Oe{fromBER(e,t,n){return t}toBER(e){return ht}};cs.override="EndOfContentValueBlock";var Sf,ls=class extends Te{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Sf=ls;C.EndOfContent=Sf;ls.NAME=Xn;var Rf,sr=class extends Te{constructor(e={}){super(e,Oe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Rf=sr;C.Null=Rf;sr.NAME="NULL";var us=class extends Mt(Oe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=z.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);return Ut(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ec.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};us.NAME="BooleanValueBlock";var If,fs=class extends Te{constructor(e={}){super(e,us),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};If=fs;C.Boolean=If;fs.NAME="BOOLEAN";var hs=class extends Mt(bt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Ef)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?bt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};hs.NAME="OctetStringValueBlock";var Tf,Pt=class r extends Te{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},hs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Vs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?or.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return z.BufferSourceConverter.concat(e)}};Tf=Pt;C.OctetString=Tf;Pt.NAME=Ef;var ds=class extends Mt(bt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Xn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==xf)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=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Vs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return bt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ht;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 Bf,ln=class extends Te{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return or.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Bf=ln;C.BitString=Bf;ln.NAME=xf;var Cf;function l0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=ts(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=ts(t,s)),s}function bf(r){if(r>=jn.length)for(let e=jn.length;e<=r;e++){let t=new Uint8Array([0]),n=jn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=ts(t,n)),jn.push(n)}return jn[r]}function u0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Zn=class extends Mt(Oe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ec.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=u0(bf(n),t),i="-";break;default:t=l0(t,bf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=wf.charAt(t[c]));return a===!1&&(i+=wf.charAt(0)),i}};Cf=Zn;Zn.NAME="IntegerValueBlock";Object.defineProperty(Cf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var kf,pe=class r extends Te{constructor(e={}){super(e,Zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return rs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){rs();let t=BigInt(e),n=new Wn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${z.Convert.ToHex(a)}`)+t,f=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};kf=pe;C.Integer=kf;pe.NAME="INTEGER";var Nf,ps=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Nf=ps;C.Enumerated=Nf;ps.NAME="ENUMERATED";var Qn=class extends Mt(Oe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){rs();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=nr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=z.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Qn.NAME="sidBlock";var ms=class extends Oe{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Qn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ht;t.push(o)}return xc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Qn;if(o>Number.MAX_SAFE_INTEGER){rs();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ms.NAME="ObjectIdentifierValueBlock";var Lf,ft=class extends Te{constructor(e={}){super(e,ms),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Lf=ft;C.ObjectIdentifier=Lf;ft.NAME="OBJECT IDENTIFIER";var Jn=class extends Mt(Dt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=z.BufferSourceConverter.toUint8Array(e);if(!Ut(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=nr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=z.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Jn.NAME="relativeSidBlock";var gs=class extends Oe{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ht;n.push(s)}return xc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};gs.NAME="RelativeObjectIdentifierValueBlock";var Df,ys=class extends Te{constructor(e={}){super(e,gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Df=ys;C.RelativeObjectIdentifier=Df;ys.NAME="RelativeObjectIdentifier";var Pf,_e=class extends or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Pf=_e;C.Sequence=Pf;_e.NAME="SEQUENCE";var Of,ws=class extends or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Of=ws;C.Set=Of;ws.NAME="SET";var bs=class extends Mt(Oe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=un}toJSON(){return{...super.toJSON(),value:this.value}}};bs.NAME="StringValueBlock";var Es=class extends bs{};Es.NAME="SimpleStringValueBlock";var $e=class extends ss{constructor({...e}={}){super(e,Es)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};$e.NAME="SIMPLE STRING";var xs=class extends $e{fromBuffer(e){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=z.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(e)),this.valueBlock.value=e}};xs.NAME="Utf8StringValueBlock";var Uf,Ot=class extends xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Uf=Ot;C.Utf8String=Uf;Ot.NAME="UTF8String";var vs=class extends $e{fromBuffer(e){this.valueBlock.value=z.Convert.ToUtf16String(e),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(e))}};vs.NAME="BmpStringValueBlock";var Mf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Mf=_s;C.BmpString=Mf;_s.NAME="BMPString";var As=class extends $e{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=nr(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};As.NAME="UniversalStringValueBlock";var Ff,Ss=class extends As{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Ff=Ss;C.UniversalString=Ff;Ss.NAME="UniversalString";var Vf,Rs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Vf=Rs;C.NumericString=Vf;Rs.NAME="NumericString";var Kf,Is=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Kf=Is;C.PrintableString=Kf;Is.NAME="PrintableString";var Hf,Ts=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Hf=Ts;C.TeletexString=Hf;Ts.NAME="TeletexString";var $f,Bs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};$f=Bs;C.VideotexString=$f;Bs.NAME="VideotexString";var qf,Cs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};qf=Cs;C.IA5String=qf;Cs.NAME="IA5String";var zf,ks=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};zf=ks;C.GraphicString=zf;ks.NAME="GraphicString";var Gf,eo=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gf=eo;C.VisibleString=Gf;eo.NAME="VisibleString";var Yf,Ns=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Yf=Ns;C.GeneralString=Yf;Ns.NAME="GeneralString";var jf,Ls=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};jf=Ls;C.CharacterString=jf;Ls.NAME="CharacterString";var Wf,to=class extends eo{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=je(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=je(this.month,2),t[2]=je(this.day,2),t[3]=je(this.hour,2),t[4]=je(this.minute,2),t[5]=je(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Wf=to;C.UTCTime=Wf;to.NAME="UTCTime";var Xf,Ds=class extends to{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(je(this.year,4)),t.push(je(this.month,2)),t.push(je(this.day,2)),t.push(je(this.hour,2)),t.push(je(this.minute,2)),t.push(je(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(je(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Xf=Ds;C.GeneralizedTime=Xf;Ds.NAME="GeneralizedTime";var Zf,Ps=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Zf=Ps;C.DATE=Zf;Ps.NAME="DATE";var Qf,Os=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Qf=Os;C.TimeOfDay=Qf;Os.NAME="TimeOfDay";var Jf,Us=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Jf=Us;C.DateTime=Jf;Us.NAME="DateTime";var eh,Ms=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};eh=Ms;C.Duration=eh;Ms.NAME="Duration";var th,Fs=class extends Ot{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};th=Fs;C.TIME=th;Fs.NAME="TIME";function h0(r){let{result:e}=fn(r),t=e.valueBlock.value;return{n:V(Et(t[1].toBigInt()),"base64url"),e:V(Et(t[2].toBigInt()),"base64url"),d:V(Et(t[3].toBigInt()),"base64url"),p:V(Et(t[4].toBigInt()),"base64url"),q:V(Et(t[5].toBigInt()),"base64url"),dp:V(Et(t[6].toBigInt()),"base64url"),dq:V(Et(t[7].toBigInt()),"base64url"),qi:V(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function d0(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 x("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new pe({value:0}),pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url"))),pe.fromBigInt(xt(L(r.d,"base64url"))),pe.fromBigInt(xt(L(r.p,"base64url"))),pe.fromBigInt(xt(L(r.q,"base64url"))),pe.fromBigInt(xt(L(r.dp,"base64url"))),pe.fromBigInt(xt(L(r.dq,"base64url"))),pe.fromBigInt(xt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function p0(r){let{result:e}=fn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:V(Et(t[0].toBigInt()),"base64url"),e:V(Et(t[1].toBigInt()),"base64url")}}function m0(r){if(r.n==null||r.e==null)throw new x("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new sr]}),new ln({valueHex:new _e({value:[pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Et(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function xt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var g0=16,_c=32,Ac=1e4;async function y0(r,e){let t=Fe.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new sr]}),new Pt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=rt(g0),a=await wc(Vn,e,i,{c:Ac,dkLen:_c}),c=rt(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new _e({value:[new Pt({valueHex:i}),new pe({value:Ac}),new pe({value:_c}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new sr]})]}),d=new _e({value:[new ft({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new ft({value:"2.16.840.1.101.3.4.1.42"}),new Pt({valueHex:c})]})]})]}),p=new _e({value:[d,new Pt({valueHex:f})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...V(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
7
|
-
`)}async function w0(r,e){let t=Fe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=fn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=b0(s),l=await wc(Vn,e,a,{c,dkLen:u}),d=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=ro(await t.subtle.decrypt({name:"AES-CBC",iv:i},d,f)),{result:p}=fn(h);n=rh(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=fn(o);n=rh(s)}else throw new x("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Sc(n)}function b0(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new x("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new x("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=ro(s.valueBlock.value[0].getValue()),a=Ac,c=_c;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new x("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new x("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=ro(u.valueBlock.value[1].getValue());return{cipherText:ro(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function rh(r){return ro(r.valueBlock.value[2].getValue())}function ro(r){return new Uint8Array(r,0,r.byteLength)}async function nh(r){let e=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await ih(e);return{privateKey:t[0],publicKey:t[1]}}async function Rc(r){let t=[await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await E0(r)],n=await ih({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function oh(r,e){let t=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function sh(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function ih(r){if(r.privateKey==null||r.publicKey==null)throw new x("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)])}async function E0(r){return Fe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ks(r){if(r.kty!=="RSA")throw new x("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new x("invalid key modulus","ERR_INVALID_KEY_MODULUS");return L(r.n,"base64url").length*8}var oo=8192,no=class{_key;constructor(e){this._key=e}verify(e,t){return sh(this._key,t,e)}marshal(){return ir.jwkToPkix(this._key)}get bytes(){return yt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}},hn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return rt(16)}sign(e){return oh(this._key,e)}get public(){if(this._publicKey==null)throw new x("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new no(this._publicKey)}marshal(){return ir.jwkToPkcs1(this._key)}get bytes(){return wt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return ir.exportToPem(this,e);if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Sc(r){let e=ir.pkcs1ToJwk(r);if(Ks(e)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Rc(e);return new hn(t.privateKey,t.publicKey)}function v0(r){let e=ir.pkixToJwk(r);if(Ks(e)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new no(e)}async function _0(r){if(Ks(r)>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Rc(r);return new hn(e.privateKey,e.publicKey)}async function A0(r){if(r>oo)throw new x("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await nh(r);return new hn(e.privateKey,e.publicKey)}var Nc={};ve(Nc,{Secp256k1PrivateKey:()=>io,Secp256k1PublicKey:()=>so,generateKeyPair:()=>U0,unmarshalSecp256k1PrivateKey:()=>P0,unmarshalSecp256k1PublicKey:()=>O0});var S0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ar=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cr=new Uint32Array(64),Tc=class extends en{constructor(){super(64,32,8,!1),this.A=ar[0]|0,this.B=ar[1]|0,this.C=ar[2]|0,this.D=ar[3]|0,this.E=ar[4]|0,this.F=ar[5]|0,this.G=ar[6]|0,this.H=ar[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)cr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=cr[l-15],h=cr[l-2],p=it(d,7)^it(d,18)^d>>>3,m=it(h,17)^it(h,19)^h>>>10;cr[l]=m+cr[l-7]+p+cr[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=it(a,6)^it(a,11)^it(a,25),h=f+d+Fu(a,c,u)+S0[l]+cr[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Vu(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(){cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ah=Fo(()=>new Tc);function ch(r){r.lowS!==void 0&&at("lowS",r.lowS),r.prehash!==void 0&&at("prehash",r.prehash)}function R0(r){let e=$n(r);gt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:I0,hexToBytes:T0}=Ho,Ft={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Ft;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Er(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Er(o.length/2|128):"";return`${Er(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Ft,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ft;if(r<Vt)throw new e("integer: negative integers are not allowed");let t=Er(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Ft;if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return I0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ft,o=typeof r=="string"?T0(r):r;tn(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Ft,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Vt=BigInt(0),Ae=BigInt(1),Z1=BigInt(2),lh=BigInt(3),Q1=BigInt(4);function B0(r){let e=R0(r),{Fp:t}=e,n=tr(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return kt(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Kn(m,Ae,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(Qt(m)&&(m=Bt(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let E;try{E=typeof m=="bigint"?m:Ct(le("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(E=Z(E,w)),Ge("private key",E,Ae,w),E}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=_r((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let E=m.is0();g==null&&(g=E?t.ONE:t.inv(w));let A=t.mul(y,g),R=t.mul(b,g),v=t.mul(w,g);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:R}}),l=_r(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=E=>t.eql(E,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(le("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return zo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:E,py:A,pz:R}=g,v=t.eql(t.mul(y,R),t.mul(E,w)),I=t.eql(t.mul(b,R),t.mul(A,w));return v&&I}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,lh),{px:w,py:E,pz:A}=this,R=t.ZERO,v=t.ZERO,I=t.ZERO,N=t.mul(w,w),ee=t.mul(E,E),H=t.mul(A,A),K=t.mul(w,E);return K=t.add(K,K),I=t.mul(w,A),I=t.add(I,I),R=t.mul(g,I),v=t.mul(b,H),v=t.add(R,v),R=t.sub(ee,v),v=t.add(ee,v),v=t.mul(R,v),R=t.mul(K,R),I=t.mul(b,I),H=t.mul(g,H),K=t.sub(N,H),K=t.mul(g,K),K=t.add(K,I),I=t.add(N,N),N=t.add(I,N),N=t.add(N,H),N=t.mul(N,K),v=t.add(v,N),H=t.mul(E,A),H=t.add(H,H),N=t.mul(H,K),R=t.sub(R,N),I=t.mul(H,ee),I=t.add(I,I),I=t.add(I,I),new d(R,v,I)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:E,py:A,pz:R}=g,v=t.ZERO,I=t.ZERO,N=t.ZERO,ee=e.a,H=t.mul(e.b,lh),K=t.mul(y,E),O=t.mul(b,A),B=t.mul(w,R),D=t.add(y,b),S=t.add(E,A);D=t.mul(D,S),S=t.add(K,O),D=t.sub(D,S),S=t.add(y,w);let _=t.add(E,R);return S=t.mul(S,_),_=t.add(K,B),S=t.sub(S,_),_=t.add(b,w),v=t.add(A,R),_=t.mul(_,v),v=t.add(O,B),_=t.sub(_,v),N=t.mul(ee,S),v=t.mul(H,B),N=t.add(v,N),v=t.sub(O,N),N=t.add(O,N),I=t.mul(v,N),O=t.add(K,K),O=t.add(O,K),B=t.mul(ee,B),S=t.mul(H,S),O=t.add(O,B),B=t.sub(K,B),B=t.mul(ee,B),S=t.add(S,B),K=t.mul(O,S),I=t.add(I,K),K=t.mul(_,S),v=t.mul(D,v),v=t.sub(v,K),K=t.mul(D,O),N=t.mul(_,N),N=t.add(N,K),new d(v,I,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){Ge("scalar",g,Vt,e.n);let y=d.ZERO;if(g===Vt)return y;if(g===Ae)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:E,k2neg:A,k2:R}=b.splitScalar(g),v=y,I=y,N=this;for(;E>Vt||R>Vt;)E&Ae&&(v=v.add(N)),R&Ae&&(I=I.add(N)),N=N.double(),E>>=Ae,R>>=Ae;return w&&(v=v.negate()),A&&(I=I.negate()),I=new d(t.mul(I.px,b.beta),I.py,I.pz),v.add(I)}multiply(g){let{endo:y,n:b}=e;Ge("scalar",g,Ae,b);let w,E;if(y){let{k1neg:A,k1:R,k2neg:v,k2:I}=y.splitScalar(g),{p:N,f:ee}=this.wNAF(R),{p:H,f:K}=this.wNAF(I);N=p.constTimeNegate(A,N),H=p.constTimeNegate(v,H),H=new d(t.mul(H.px,y.beta),H.py,H.pz),w=N.add(H),E=ee.add(K)}else{let{p:A,f:R}=this.wNAF(g);w=A,E=R}return d.normalizeZ([w,E])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,E=(R,v)=>v===Vt||v===Ae||!R.equals(w)?R.multiplyUnsafe(v):R.multiply(v),A=E(this,y).add(E(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===Ae)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===Ae?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return at("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return at("isCompressed",g),Bt(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=qo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function C0(r){let e=$n(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function uh(r){let e=C0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(B){return Z(B,n)}function a(B){return $o(B,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=B0({...e,toBytes(B,D,S){let _=D.toAffine(),T=t.toBytes(_.x),P=kt;return at("isCompressed",S),S?P(Uint8Array.from([D.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,t.toBytes(_.y))},fromBytes(B){let D=B.length,S=B[0],_=B.subarray(1);if(D===o&&(S===2||S===3)){let T=Ct(_);if(!Kn(T,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(T),U;try{U=t.sqrt(P)}catch(G){let q=G instanceof Error?": "+G.message:"";throw new Error("Point is not on curve"+q)}let M=(U&Ae)===Ae;return(S&1)===1!==M&&(U=t.neg(U)),{x:T,y:U}}else if(D===s&&S===4){let T=t.fromBytes(_.subarray(0,t.BYTES)),P=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:T,y:P}}else throw new Error(`Point of length ${D} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=B=>Bt(er(B,e.nByteLength));function h(B){let D=n>>Ae;return B>D}function p(B){return h(B)?i(-B):B}let m=(B,D,S)=>Ct(B.slice(D,S));class g{constructor(D,S,_){this.r=D,this.s=S,this.recovery=_,this.assertValidity()}static fromCompact(D){let S=e.nByteLength;return D=le("compactSignature",D,S*2),new g(m(D,0,S),m(D,S,2*S))}static fromDER(D){let{r:S,s:_}=Ft.toSig(le("DER",D));return new g(S,_)}assertValidity(){Ge("r",this.r,Ae,n),Ge("s",this.s,Ae,n)}addRecoveryBit(D){return new g(this.r,this.s,D)}recoverPublicKey(D){let{r:S,s:_,recovery:T}=this,P=R(le("msgHash",D));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");let U=T===2||T===3?S+e.n:S;if(U>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=T&1?"03":"02",$=c.fromHex(M+d(U)),G=a(U),q=i(-P*G),X=i(_*G),J=c.BASE.multiplyAndAddUnsafe($,q,X);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return xr(this.toDERHex())}toDERHex(){return Ft.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return xr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(B){try{return u(B),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let B=Ya(e.n);return ju(e.randomBytes(B),e.n)},precompute(B=8,D=c.BASE){return D._setWindowSize(B),D.multiply(BigInt(3)),D}};function b(B,D=!0){return c.fromPrivateKey(B).toRawBytes(D)}function w(B){let D=Qt(B),S=typeof B=="string",_=(D||S)&&B.length;return D?_===o||_===s:S?_===2*o||_===2*s:B instanceof c}function E(B,D,S=!0){if(w(B))throw new Error("first arg must be private key");if(!w(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(u(B)).toRawBytes(S)}let A=e.bits2int||function(B){let D=Ct(B),S=B.length*8-e.nBitLength;return S>0?D>>BigInt(S):D},R=e.bits2int_modN||function(B){return i(A(B))},v=Hn(e.nBitLength);function I(B){return Ge(`num < 2^${e.nBitLength}`,B,Vt,v),er(B,e.nByteLength)}function N(B,D,S=ee){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:T}=e,{lowS:P,prehash:U,extraEntropy:M}=S;P==null&&(P=!0),B=le("msgHash",B),ch(S),U&&(B=le("prehashed msgHash",_(B)));let $=R(B),G=u(D),q=[I(G),I($)];if(M!=null&&M!==!1){let xe=M===!0?T(t.BYTES):M;q.push(le("extraEntropy",xe))}let X=kt(...q),J=$;function Ee(xe){let Se=A(xe);if(!l(Se))return;let Me=a(Se),me=c.BASE.multiply(Se).toAffine(),ze=i(me.x);if(ze===Vt)return;let _t=i(Me*i(J+ze*G));if(_t===Vt)return;let Ln=(me.x===ze?0:2)|Number(me.y&Ae),Dn=_t;return P&&h(_t)&&(Dn=p(_t),Ln^=1),new g(ze,Dn,Ln)}return{seed:X,k2sig:Ee}}let ee={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};function K(B,D,S=ee){let{seed:_,k2sig:T}=N(B,D,S),P=e;return $a(P.hash.outputLen,P.nByteLength,P.hmac)(_,T)}c.BASE._setWindowSize(8);function O(B,D,S,_=H){let T=B;if(D=le("msgHash",D),S=le("publicKey",S),"strict"in _)throw new Error("options.strict was renamed to lowS");ch(_);let{lowS:P,prehash:U}=_,M,$;try{if(typeof T=="string"||Qt(T))try{M=g.fromDER(T)}catch(me){if(!(me instanceof Ft.Err))throw me;M=g.fromCompact(T)}else if(typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint"){let{r:me,s:ze}=T;M=new g(me,ze)}else throw new Error("PARSE");$=c.fromHex(S)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&M.hasHighS())return!1;U&&(D=e.hash(D));let{r:G,s:q}=M,X=R(D),J=a(q),Ee=i(X*J),xe=i(G*J),Se=c.BASE.multiplyAndAddUnsafe($,Ee,xe)?.toAffine();return Se?i(Se.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:E,sign:K,verify:O,ProjectivePoint:c,Signature:g,utils:y}}function k0(r){return{hash:r,hmac:(e,...t)=>Yn(r,e,Pa(...t)),randomBytes:Jr}}function fh(r,e){let t=n=>uh({...r,...k0(n)});return Object.freeze({...t(e),create:t})}var ph=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),hh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),N0=BigInt(1),Bc=BigInt(2),dh=(r,e)=>(r+e/Bc)/e;function L0(r){let e=ph,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ne(f,t,e)*f%e,d=ne(l,t,e)*f%e,h=ne(d,Bc,e)*u%e,p=ne(h,o,e)*h%e,m=ne(p,s,e)*p%e,g=ne(m,a,e)*m%e,y=ne(g,c,e)*g%e,b=ne(y,a,e)*m%e,w=ne(b,t,e)*f%e,E=ne(w,i,e)*p%e,A=ne(E,n,e)*u%e,R=ne(A,Bc,e);if(!Cc.eql(Cc.sqr(R),r))throw new Error("Cannot find square root");return R}var Cc=tr(ph,void 0,void 0,{sqrt:L0}),dt=fh({a:BigInt(0),b:BigInt(7),Fp:Cc,n:hh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=hh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-N0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=dh(s*r,e),c=dh(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},ah),av=BigInt(0);var cv=dt.ProjectivePoint;function mh(){return dt.utils.randomPrivateKey()}function gh(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(tt(t))return t.then(({digest:n})=>dt.sign(n,r).toDERRawBytes()).catch(n=>{throw new x(String(n),"ERR_INVALID_INPUT")});try{return dt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new x(String(n),"ERR_INVALID_INPUT")}}function yh(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(tt(n))return n.then(({digest:o})=>dt.verify(e,o,r)).catch(o=>{throw new x(String(o),"ERR_INVALID_INPUT")});try{return dt.verify(e,n.digest,r)}catch(o){throw new x(String(o),"ERR_INVALID_INPUT")}}function wh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function bh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new x(String(e),"ERR_INVALID_PRIVATE_KEY")}}function kc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new x(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Eh(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new x(String(e),"ERR_INVALID_PRIVATE_KEY")}}var so=class{_key;constructor(e){kc(e),this._key=e}verify(e,t){return yh(this._key,t,e)}marshal(){return wh(this._key)}get bytes(){return yt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return tt(e)?{bytes:t}=await e:t=e.bytes,t}},io=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Eh(e),bh(this._key),kc(this._publicKey)}sign(e){return gh(this._key,e)}get public(){return new so(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return tt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return V(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return on(this.bytes,e);throw new x(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function P0(r){return new io(r)}function O0(r){return new so(r)}async function U0(){let r=mh();return new io(r)}var lr={rsa:Ic,ed25519:yc,secp256k1:Nc};function Lc(r){let e=Object.keys(lr).join(" / ");return new x(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Dc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return lr[r];throw Lc(r)}async function xh(r,e){return Dc(r).generateKeyPair(e??2048)}function ao(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return lr.rsa.unmarshalRsaPublicKey(t);case oe.Ed25519:return lr.ed25519.unmarshalEd25519PublicKey(t);case oe.Secp256k1:return lr.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Lc(e.Type??"unknown")}}function vh(r,e){return e=(e??"rsa").toLowerCase(),Dc(e),r.bytes}async function co(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return lr.rsa.unmarshalRsaPrivateKey(t);case oe.Ed25519:return lr.ed25519.unmarshalEd25519PrivateKey(t);case oe.Secp256k1:return lr.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Lc(e.Type??"RSA")}}function _h(r,e){return e=(e??"rsa").toLowerCase(),Dc(e),r.bytes}function M0(r,e){try{if(typeof r=="string"&&r.length>0)return F0(r);if(typeof r=="number"&&isFinite(r))return e?.long?K0(r):V0(r);throw new Error("Value is not a string or number.")}catch(t){let n=H0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function F0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var $s=M0;function V0(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function K0(r){let e=Math.abs(r);return e>=864e5?Hs(r,e,864e5,"day"):e>=36e5?Hs(r,e,36e5,"hour"):e>=6e4?Hs(r,e,6e4,"minute"):e>=1e3?Hs(r,e,1e3,"second"):`${r} ms`}function Hs(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function H0(r){return typeof r=="object"&&r!==null&&"message"in r}function Pc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=$s,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let E=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(R,v)=>{if(R==="%%")return"%";E++;let I=t.formatters[v];if(typeof I=="function"){let N=g[E];R=I.call(y,N),g.splice(E,1),E--}return R}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var qs=W0(),$0=["#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 q0(){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 z0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+$s(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var G0=console.debug??console.log??(()=>{});function Y0(r){try{r?qs?.setItem("debug",r):qs?.removeItem("debug")}catch{}}function j0(){let r;try{r=qs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function W0(){try{return localStorage}catch{}}function X0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Ah=Pc({formatArgs:z0,save:Y0,load:j0,useColors:q0,setupFormatters:X0,colors:$0,storage:qs,log:G0});var Ze=Ah;Ze.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);Ze.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ze.formatters.m=r=>r==null?"undefined":Mn.baseEncode(r);Ze.formatters.p=r=>r==null?"undefined":r.toString();Ze.formatters.c=r=>r==null?"undefined":r.toString();Ze.formatters.k=r=>r==null?"undefined":r.toString();Ze.formatters.a=r=>r==null?"undefined":r.toString();function Z0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function zs(){return{forComponent(r){return Q0(r)}}}function Q0(r){let e=Z0(`${r}:trace`);return Ze.enabled(`${r}:trace`)&&Ze.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Ze(`${r}:trace`)),Object.assign(Ze(r),{error:Ze(`${r}:error`),trace:e})}var Rh=Symbol.for("nodejs.util.inspect.custom"),Sh=Object.values(jt).map(r=>r.decoder).reduce((r,e)=>r.or(e),jt.identity.decoder),Ih=114,Mc=36,Fc=37,lo=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[No]=!0;toString(){return this.string==null&&(this.string=ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return et.createV1(Ih,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Rh](){return`PeerId(${this.toString()})`}},Cr=class extends lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},kr=class extends lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Nr=class extends lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Oc=2336,Uc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=It.digest(L(this.url))}[Rh](){return`PeerId(${this.url})`}[No]=!0;toString(){return this.toCID().toString()}toCID(){return et.createV1(Oc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};function Th(r){if(r.type==="RSA")return new Cr(r);if(r.type==="Ed25519")return new kr(r);if(r.type==="secp256k1")return new Nr(r);throw new x("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??Sh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=yr(ae.decode(`z${r}`));return r.startsWith("12D")?new kr({multihash:t}):r.startsWith("16U")?new Nr({multihash:t}):new Cr({multihash:t})}return dn(Sh.decode(r))}function dn(r){try{let e=yr(r);if(e.code===It.code){if(e.digest.length===Mc)return new kr({multihash:e});if(e.digest.length===Fc)return new Nr({multihash:e})}if(e.code===Re.code)return new Cr({multihash:e})}catch{return J0(et.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function J0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ih&&r.code!==Oc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Oc){let t=V(r.multihash.digest);return new Uc(new URL(t))}let e=r.multihash;if(e.code===Re.code)return new Cr({multihash:r.multihash});if(e.code===It.code){if(e.digest.length===Mc)return new kr({multihash:r.multihash});if(e.digest.length===Fc)return new Nr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function pn(r,e){return r.length===Mc?new kr({multihash:mt(It.code,r),privateKey:e}):r.length===Fc?new Nr({multihash:mt(It.code,r),privateKey:e}):new Cr({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function mn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Qe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return mn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var Kt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Lh=Symbol.for("@achingbrain/uint8arraylist");function Nh(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ys(r){return!!r?.[Lh]}var we=class r{bufs;length;[Lh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ys(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ys(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Nh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Nh(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ys(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ie(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ie(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ys(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=st(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=st(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=st(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Vc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Vc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=st(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function Lr(r,e){return Math.floor(Math.random()*(e-r))+r}var Dr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=Lr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Kc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Dh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ph=new globalThis.TextEncoder;function ey(r,e){let t=Kc[e],n=Dh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ty(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Kc[e],o=Dh[e],s=r;for(;s.length>0;){let i=Ph.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Hc(r,{size:e=32,utf8Buffer:t}={}){if(!Kc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return ty(r,e,t);r=Ph.encode(r)}return ey(r,e)}var ry=gr(kh(),1);var fo={hash:r=>Number(Hc(r,{size:32})),hashV:(r,e)=>ny(fo.hash(r,e))};function ny(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var oy=500,ho=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??fo,this.seed=e.seed??Lr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Dr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Dr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Lr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Dr(this.bucketSize));for(let a=0;a<oy;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Dr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},sy={1:.5,2:.84,4:.95,8:.98};function iy(r=.001){return r>.002?2:r>1e-5?4:8}function Oh(r,e=.001){let t=iy(e),n=sy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Vc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var js=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??fo,this.seed=e.seed??Lr(0,Math.pow(2,10)),this.filterSeries=[new ho({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ho({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function $c(r,e=.001,t){return new js({...Oh(r,e),...t??{}})}var Uh=async()=>{let r=await xh("Ed25519"),e=await ay(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function ay(r){return pn(vh(r.public),_h(r))}var Mh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var po;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(po||(po={}));var gn=class r{static createFromProtobuf=async e=>{let t=po.decode(e),n=await pn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Fh(n,o,s),c=await(await co(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new x("envelope signature is not valid for the given domain",Mh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=po.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return te(this.marshal(),e.marshal())}async validate(e){let t=Fh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return ao(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Fh=(r,e,t)=>{let n=L(r),o=De(n.byteLength),s=De(e.length),i=De(t.length);return new we(o,n,s,e,i,t)};function Vh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ws=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Kh=45,cy=15,yn=new Ws;function qc(r){if(!(r.length>cy))return yn.new(r).parseWith(()=>yn.readIPv4Addr())}function zc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Kh))return yn.new(r).parseWith(()=>yn.readIPv6Addr())}function Xs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Kh))return yn.new(r).parseWith(()=>yn.readIPAddr())}var aA=parseInt("0xFFFF",16),cA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function wn(r){return!!qc(r)}function bn(r){return!!zc(r)}function Zs(r){return!!Xs(r)}var qh=wn,dy=bn,Gc=function(r){let e=0;if(r=r.toString().trim(),qh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(dy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=qh(t[n]),i;s&&(i=Gc(t[n]),t[n]=V(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,V(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},zh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var En={},Yc={},my=[[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"]];my.forEach(r=>{let e=gy(...r);Yc[e.code]=e,En[e.name]=e});function gy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(Yc[r]!=null)return Yc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(En[r]!=null)return En[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var zA=W("ip4"),GA=W("ip6"),YA=W("ipcidr");function Zc(r,e){switch(W(r).code){case 4:case 41:return wy(e);case 42:return Xc(e);case 6:case 273:case 33:case 132:return jh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Xc(e);case 421:return vy(e);case 444:return Yh(e);case 445:return Yh(e);case 466:return xy(e);case 481:return globalThis.encodeURIComponent(Xc(e));default:return V(e,"base16")}}function Qc(r,e){switch(W(r).code){case 4:return Gh(e);case 41:return Gh(e);case 42:return Wc(e);case 6:case 273:case 33:case 132:return Jc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wc(e);case 421:return by(e);case 444:return _y(e);case 445:return Ay(e);case 466:return Ey(e);case 481:return Wc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var jc=Object.values(jt).map(r=>r.decoder),yy=function(){let r=jc[0].or(jc[1]);return jc.slice(2).forEach(e=>r=r.or(e)),r}();function Gh(r){if(!Zs(r))throw new Error("invalid ip address");return Gc(r)}function wy(r){let e=zh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Zs(e))throw new Error("invalid ip address");return e}function Jc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function jh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wc(r){let e=L(r),t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function Xc(r){let e=lt(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return V(r)}function by(r){let e;r[0]==="Q"||r[0]==="1"?e=yr(ae.decode(`z${r}`)).bytes:e=et.parse(r).multihash.bytes;let t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function Ey(r){let e=yy.decode(r),t=Uint8Array.from(De(e.length));return Ie([t,e],t.length+e.length)}function xy(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+V(t,"base64url")}function vy(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return V(t,"base58btc")}function _y(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=We.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Jc(n);return Ie([t,o],t.length+o.length)}function Ay(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Jc(n);return Ie([t,o],t.length+o.length)}function Yh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=V(e,"base32"),o=jh(t);return`${n}:${o}`}function Wh(r){r=el(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=W(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Zh("invalid address: "+r);if(a.path===!0){n=el(o.slice(s).join("/")),e.push([a.code,Qc(a.code,n)]),t.push([a.code,n]);break}let c=Qc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Zc(a.code,c)])}return{string:Xh(t),bytes:rl(e),tuples:e,stringTuples:t,path:n}}function tl(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=de(s),a=W(s),c=Sy(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Zh("Invalid address Uint8Array: "+V(r,"base16"));e.push([s,u]);let f=Zc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Xh(t),tuples:e,stringTuples:t,path:n}}function Xh(r){let e=[];return r.map(t=>{let n=W(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),el(e.join("/"))}function rl(r){return Ie(r.map(e=>{let t=W(e[0]),n=Uint8Array.from(De(t.code));return e.length>1&&e[1]!=null&&(n=Ie([n,e[1]])),n}))}function Sy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=lt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function el(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Zh(r){return new Error("Error parsing address: "+r)}var Ry=Symbol.for("nodejs.util.inspect.custom"),nl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Iy=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],Qs=class r{bytes;#e;#t;#s;#a;[nl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=tl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Wh(e)}else if(ur(e))t=tl(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),f=W("dns6"),l=W("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),Iy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=W(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=W(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},W(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>W(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(rl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===En.p2p.code&&e.push([n,o]),n===En["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?V(ae.decode(`z${n}`),"base58btc"):V(et.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=xn.get(t.name);if(n==null)throw new x(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>se(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Ry](){return`Multiaddr(${this.#e})`}};var xn=new Map;function ur(r){return!!r?.[nl]}function se(r){return new Qs(r)}var Qh="libp2p-peer-record",Jh=Uint8Array.from([3,1]);var mo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Ke(s,n.codec()),n.decode=s=>Ve(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=He((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Ke(n,r.codec()),r.decode=n=>Ve(n,r.codec())})(mo||(mo={}));var Pr=class r{static createFromProtobuf=e=>{let t=mo.decode(e),n=dn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Qh;static CODEC=Jh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=mo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Vh(this.multiaddrs,e.multiaddrs))}};function Ty(r){return r[Symbol.asyncIterator]!=null}function By(r){if(Ty(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var go=By;var sl=gr(td(),1);var wo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},rd=r=>globalThis.DOMException===void 0?new il(r):new DOMException(r),nd=r=>{let e=r.reason===void 0?rd("This operation was aborted."):r.reason;return e instanceof Error?e:rd(e)};function bo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&f(nd(d)),d.addEventListener("abort",()=>{f(nd(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new wo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function al(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Eo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=al(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var fr=class extends sl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Eo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#_(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=bo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof wo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var hr={},vn=r=>{r.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vn.dispatchEvent("message",r,e)})};vn.addEventListener=(r,e)=>{hr[r]==null&&(hr[r]=[]),hr[r].push(e)};vn.removeEventListener=(r,e)=>{hr[r]!=null&&(hr[r]=hr[r].filter(t=>t===e))};vn.dispatchEvent=function(r,e,t){hr[r]!=null&&hr[r].forEach(n=>n(e,t))};var cl=vn;var ll="lock:worker:request-read",ul="lock:worker:release-read",fl="lock:master:grant-read",hl="lock:worker:request-write",dl="lock:worker:release-write",pl="lock:master:grant-write";var od=(r=21)=>Math.random().toString().substring(2);var sd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},id=(r,e,t,n)=>async()=>{let o=od();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},Ny={singleProcess:!1},ad=r=>{if(r=Object.assign({},Ny,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return cl.addEventListener("message",sd(t,"requestReadLock",ll,ul,fl)),cl.addEventListener("message",sd(t,"requestWriteLock",hl,dl,pl)),t}return{isWorker:!0,readLock:t=>id(t,ll,fl,ul),writeLock:t=>id(t,hl,pl,dl)}};var Or={},dr;async function ml(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>bo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Ly=(r,e)=>{if(dr.isWorker===!0)return{readLock:dr.readLock(r,e),writeLock:dr.writeLock(r,e)};let t=new fr({concurrency:1}),n;return{async readLock(){if(n!=null)return ml(n,e);n=new fr({concurrency:e.concurrency,autoStart:!1});let o=n,s=ml(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,ml(t,e)}}},Dy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function gl(r){let e=Object.assign({},Dy,r);return dr==null&&(dr=ad(e),dr.isWorker!==!0&&(dr.addEventListener("requestReadLock",t=>{Or[t.data.name]!=null&&Or[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),dr.addEventListener("requestWriteLock",async t=>{Or[t.data.name]!=null&&Or[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Or[e.name]==null&&(Or[e.name]=Ly(e.name,e)),Or[e.name]}var Be={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var _n;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=He((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=He((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),ti.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=ti.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=He((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ei.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(ei.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ke(o,r.codec()),r.decode=o=>Ve(o,r.codec())})(_n||(_n={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(ei||(ei={}));var ti;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(ti||(ti={}));function An(r,e){let t=_n.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Th({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ht="/",cd=new TextEncoder().encode(Ht),ri=cd[0],Ur=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ri)throw new Error("Invalid key")}toString(e="utf8"){return V(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ht))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=cd),this._buf[0]!==ri){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ri,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ri;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ht).slice(1)}type(){return Py(this.baseNamespace())}name(){return Oy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ht)||(e+=Ht),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ht):new r(e.slice(0,-1).join(Ht))}child(e){return this.toString()===Ht?e:e.toString()===Ht?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Uy(e.map(t=>t.namespaces()))])}};function Py(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Oy(r){let e=r.split(":");return e[e.length-1]}function Uy(r){return[].concat(...r)}var yl="/peers/";function Sn(r){if(!Lo(r)||r.type==null)throw new x("Invalid PeerId",Be.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Ur(`${yl}${e}`)}async function ld(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!ur(o.multiaddr))throw new x("Multiaddr was invalid",Be.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function oi(r,e,t,n){if(e==null)throw new x("Invalid PeerData",Be.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(e.publicKey,r.publicKey))throw new x("publicKey bytes do not match peer id publicKey bytes",Be.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new x("peer id did not match existing peer id",Be.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ni(l,{validate:ud})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ni(l,{validate:fd,map:hd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[d,h]of l)h==null?a.delete(d):a.set(d,h);a=ni([...a.entries()],{validate:ud})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),d=new Map(c);for(let[h,p]of l)p==null?d.delete(h):d.set(h,p);c=ni([...d.entries()],{validate:fd,map:hd})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await ld(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,d)=>l.localeCompare(d)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function ni(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function ud(r,e){if(typeof r!="string")throw new x("Metadata key must be a string",Be.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new x("Metadata value must be a Uint8Array",Be.ERR_INVALID_PARAMETERS)}function fd(r,e){if(typeof r!="string")throw new x("Tag name must be a string",Be.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new x("Tag value must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new x("Tag value must be between 0-100",Be.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new x("Tag ttl must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new x("Tag ttl must be between greater than 0",Be.ERR_INVALID_PARAMETERS)}}function hd(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function si(r,e,t){let n=r.toString().split("/")[2],o=We.decode(n),s=dn(o),i=t.get(s);if(i!=null)return i;let a=An(s,e);return t.set(s,a),a}function My(r,e){return r==null?{}:{prefix:yl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(si(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(si(n.key,n.value,e),si(o.key,o.value,e)))}}var ii=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=gl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Sn(e))}async delete(e){if(this.peerId.equals(e))throw new x("Cannot delete self peer",Be.ERR_INVALID_PARAMETERS);await this.datastore.delete(Sn(e))}async load(e){let t=await this.datastore.get(Sn(e));return An(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await oi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Qe;for await(let{key:n,value:o}of this.datastore.query(My(e??{},t))){let s=si(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Sn(e)),n=An(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=_n.encode(t);return n!=null&&te(s,n)?{peer:An(e,s),previous:o,updated:!1}:(await this.datastore.put(Sn(e),s),{peer:An(e,s),previous:o,updated:!0})}};var ai=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new ii(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await go(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await gn.openAndCertify(e,Pr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Pr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await gn.createFromProtobuf(s.peerRecordEnvelope),a=Pr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Fy(r){return r[Symbol.asyncIterator]!=null}function Vy(r){if(Fy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var wl=Vy;function Ky(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var dd=Ky;function Hy(r){return r[Symbol.asyncIterator]!=null}function $y(r,e){let t=0;if(Hy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=dd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Mr=$y;function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r,e){return qy(r)?async function*(){yield*(await go(r)).sort(e)}():function*(){yield*go(r).sort(e)}()}var bl=zy;function Gy(r){return r[Symbol.asyncIterator]!=null}function Yy(r,e){return Gy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var El=Yy;var ci=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await wl(this.putMany(e,n)),e=[],await wl(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>bl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Mr(n,()=>o++>=s)}return e.limit!=null&&(n=El(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>bl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Mr(n,()=>s++>=o)}return e.limit!=null&&(n=El(n,e.limit)),n}};var yd=gr(gd(),1);function wd(r){return r=r??new Error("Not Found"),(0,yd.default)(r,"ERR_NOT_FOUND")}var li=class extends ci{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw wd();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Ur(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Ur(e)}};function bd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Xy=r=>r;function xl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var ui=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Xy,this._updatePeerStoreAddresses=bd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=xl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var vl=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=zs())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>pu(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Zy=["metrics","connectionProtector","dns"],Qy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ed(r={}){let e=new vl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Qy.includes(o)){let i=e.components[o];if(i==null&&!Zy.includes(o))throw new x(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function xd(r){let e={};for(let t of Object.values(r.components))for(let n of Jy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of ew(t))if(e[n]!==!0)throw new x(`Service "${tw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function Jy(r){return Array.isArray(r?.[Pn])?r[Pn]:[]}function ew(r){return Array.isArray(r?.[ha])?r[ha]:[]}function tw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var _d=gr(vd(),1),rw=["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"],nw=rw.map(r=>new _d.Netmask(r));function _l(r){for(let e of nw)if(e.contains(r))return!0;return!1}function ow(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sw(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return _l(o)}function iw(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aw(r){let e=r.split(":"),t=e[e.length-1];return _l(t)}function cw(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 fi(r){return wn(r)?_l(r):ow(r)?sw(r):iw(r)?aw(r):bn(r)?cw(r):void 0}function Ad(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!fi(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var lw=r=>r.toString().split("/").slice(1),vo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>vo(t=>t===r).match(e),pattern:r}),pi=()=>({match:r=>vo(e=>typeof e=="string").match(r),pattern:"{string}"}),mi=()=>({match:r=>vo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ce=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ae.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),hi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ba.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),ot=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=lw(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var Sl=Q(Y("dns4"),pi()),Rl=Q(Y("dns6"),pi()),Il=Q(Y("dnsaddr"),pi()),Sd=Q(Y("dns"),pi()),wR=fe(Sl),bR=fe(Rl),ER=fe(Il),xR=fe(ot(Sd,Il,Sl,Rl)),Rd=Q(Y("ip4"),vo(wn)),Id=Q(Y("ip6"),vo(bn)),Td=ot(Rd,Id),vt=ot(Td,Sd,Sl,Rl,Il),vR=fe(vt),_R=fe(Rd),AR=fe(Id),SR=fe(Td),Tl=Q(vt,Y("tcp"),mi()),_o=Q(vt,Y("udp"),mi()),RR=fe(Tl),IR=fe(_o),Bl=Q(_o,Y("quic")),gi=Q(_o,Y("quic-v1")),uw=ot(Bl,gi),TR=fe(Bl),BR=fe(gi),Al=ot(vt,Tl,_o,Bl,gi),Bd=ot(Q(Al,Y("ws"),be(Ce()))),CR=fe(Bd),Cd=ot(Q(Al,Y("wss"),be(Ce())),Q(Al,Y("tls"),Y("ws"),be(Ce()))),kR=fe(Cd),kd=Q(_o,Y("webrtc-direct"),be(hi()),be(hi()),be(Ce())),NR=fe(kd),Nd=Q(gi,Y("webtransport"),be(hi()),be(hi()),be(Ce())),LR=fe(Nd),di=ot(Bd,Cd,Q(Tl,be(Ce())),Q(uw,be(Ce())),Q(vt,be(Ce())),kd,Nd,Ce()),DR=fe(di),fw=Q(di,Y("p2p-circuit"),Ce()),Ao=fe(fw),hw=ot(Q(di,Y("p2p-circuit"),Y("webrtc"),be(Ce())),Q(di,Y("webrtc"),be(Ce())),Y("webrtc")),PR=fe(hw),dw=ot(Q(vt,Y("tcp"),mi(),Y("http"),be(Ce())),Q(vt,Y("http"),be(Ce()))),OR=fe(dw),pw=ot(Q(vt,Y("tcp"),ot(Q(Y("443"),Y("http")),Q(mi(),Y("https"))),be(Ce())),Q(vt,Y("tls"),Y("http"),be(Ce())),Q(vt,Y("https"),be(Ce()))),UR=fe(pw);function Cl(r){try{let{address:e}=r.nodeAddress();return!!fi(e)}catch{return!0}}function mw(r,e){let t=Cl(r.multiaddr),n=Cl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function gw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function yw(r,e){let t=Ao.exactMatch(r.multiaddr),n=Ao.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rn(r,e){let t=mw(r,e);if(t!==0)return t;let n=yw(r,e);return n!==0?n:gw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function yi(r){let e=[Je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var kl=60;function wi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Je[e.type],TTL:e.TTL??e.ttl??kl,data:e.data instanceof Uint8Array?V(e.data):e.data}))}}var ww=4;function Nl(r,e={}){let t=new fr({concurrency:e.queryConcurrency??ww});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),yi(o.types).forEach(a=>{s.append("type",Je[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wi(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ld(){return[Nl("https://cloudflare-dns.com/dns-query"),Nl("https://dns.google/resolve")]}var Od=gr(Pd(),1);var Ll=class{lru;constructor(e){this.lru=(0,Od.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return wi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Je[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??kl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Ud(r){return new Ll(r)}var bw=1e3,bi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Ud(e.cacheSize??bw),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ld())}async query(e,t={}){let n=yi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Je||(Je={}));function Md(r={}){return new bi(r)}var Ew=32,{code:xw}=W("dnsaddr"),Fr=async function(e,t={}){let n=t.maxRecursiveDepth??Ew;if(n===0)throw new x("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===xw)??[],i=await(t?.dns??Md()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Je.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Yd=gr(Gd(),1),vi=Yd.default;var $t;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})($t||($t={}));var k;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(k||(k={}));var Iw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Fr},addressSorter:Rn},transportManager:{faultTolerance:zt.FATAL_ALL}};async function jd(r){let e=vi(Iw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new x($t.ERR_PROTECTOR_REQUIRED,k.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await pn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new x("Private key doesn't match peer id",k.ERR_INVALID_KEY);return e}var Wd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Tw=new WeakMap;function Bw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Wd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Wd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Tw.set(l,()=>{c(s),s=null,i()}),l}}var Cw=Bw(),Xd=Cw;var _i=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Pl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new x("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Xd(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Pl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function Ai(r){if(Lo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!ur(n))throw new x("Invalid Multiaddr",k.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new x("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e?.equals(s)!==!0)throw new x("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Si=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Bn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Si(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Si(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ol=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ri(r={}){return kw(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function kw(r,e){e=e??{};let t=e.onEnd,n=new Bn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new Bn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new Bn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((E,A)=>{w=()=>{A(new Ol)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var Ul=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Cn(r,e,t,n){let o=new Ul(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Ii=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function pr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Ii(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Ii(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ti=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Bi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Nw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ie(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Gt),this.cleanup())}async join(e={}){let t=new Ti(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await pr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var kn=class extends St{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new Bi(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Gt)}),this.clear()}async onEmpty(e){this.size!==0&&await Cn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Cn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Cn(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ri({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new x("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ci=class extends kn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ki="last-dial-failure";var Ni=5,Li=100,Di=50,Pi=1e3*60*7;var Vr={minConnections:Ni,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Pi,autoDialDiscoveredPeersDebounce:10},Oi=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Vr.minConnections,this.autoDialPriority=t.autoDialPriority??Vr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Vr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Vr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Vr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Vr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ci({concurrency:t.autoDialConcurrency??Vr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Kt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Qe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,d=i.get(f.id)??0;return l>d?-1:l<d?1:0}).filter(u=>{let f=u.metadata.get(ki);if(f==null)return!0;let l=parseInt(V(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Dw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Zd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Dw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Qd={maxConnections:Li,allow:[]},Ui=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Qd.maxConnections,this.allow=t.allow??Qd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Qe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await Zd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Mi=class extends kn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Kr(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function Jd(r,e){let t=!1;for(let o of xn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var So={addressSorter:Rn,maxParallelDials:Di,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Fr}},Fi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??So.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??So.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??So.maxDialQueueLength,this.dialTimeout=t.dialTimeout??So.dialTimeout,this.connections=t.connections??new Qe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))xn.set(n,o);this.queue=new Mi({concurrency:t.maxParallelDials??So.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ai(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new x("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("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 x("Peer had more than maxPeerAddrsToDial",k.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",d.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[ki]:L(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new x(h.message,Po);l.push(h)}}throw l.length===1?l[0]:new Do(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??zl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Kr([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ie(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new x("Tried to dial self",k.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new x("The dial request is blocked by gater.allowDialPeer",k.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.code!==k.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.code!==k.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await Jd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new x("The dial request has no valid addresses",k.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new x("The connection gater denied all addresses in the dial request",k.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!Ao.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var zl=50,qt={minConnections:Ni,maxConnections:Li,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Pi,autoDialDiscoveredPeersDebounce:10},Vi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??qt.maxConnections;let n=t.minConnections??qt.minConnections;if(this.maxConnections<n)throw new x("Connection Manager maxConnections must be greater than minConnections",k.ERR_INVALID_PARAMETERS);this.connections=new Qe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>se(o)),this.deny=(t.deny??[]).map(o=>se(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??qt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new _i({points:t.inboundConnectionThreshold??qt.inboundConnectionThreshold,duration:1}),this.autoDial=new Oi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??qt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??qt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??qt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??qt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??qt.autoDialMaxQueueLength}),this.connectionPruner=new Ui({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Fi(e,{addressSorter:t.addressSorter??Rn,maxParallelDials:t.maxParallelDials??Di,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Fr},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(du)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new x("Not started",k.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=Ai(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),t.onProgress?.(new he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??zl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>se(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Nn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Uw=1.2,Mw=2,Fw=2e3,Ki=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Nn(e.interval??5e3),this.failure=new Nn(e.interval??5e3),this.next=new Nn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Mw,this.timeoutMultiplier=e.timeoutMultiplier??Uw,this.minTimeout=e.minTimeout??Fw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Kr([e.signal,n]);return ie(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Gl=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await pr(this.readNext.promise,t?.signal,t)}};function ep(){return new Gl}var Hi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Yl=class extends Error{code;constructor(e,t){super(e),this.code=t}},jl=class extends Yl{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function $i(r,e){let t=ep();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new jl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new we:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new Hi("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Vw=1e4,Kw="1.0.0",Hw="ping",$w="ipfs",tp=32,qi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??$w}/${Hw}/${Kw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Vw,this.timeout=new Ki({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Pn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=$i(o);t=Date.now(),await Promise.all([s.write(rt(tp),{signal:n}),s.read(tp,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function qw(r){return r[Symbol.asyncIterator]!=null}function zw(...r){let e=[];for(let t of r)qw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ri({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Ro=zw;var zi=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new x("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Kt;for await(let s of Ro(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new x("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new x($t.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new x($t.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Gi=globalThis.CustomEvent??Event;async function*Wl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ue(),a=ue(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ue(),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 Gi("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new Gi("task-complete"))})}c=!0,o.dispatchEvent(new Gi("task-complete"))}catch(p){u=p,o.dispatchEvent(new Gi("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=ue(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var Yi=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new x("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new x("Should not try to find self",k.ERR_FIND_SELF);let n=this,o=Ro(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new x($t.NOT_FOUND,k.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new x("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=$c(1024);for await(let s of Wl(async function*(){let i=Ro(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var ji=class extends St{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Kr([this.shutdownController.signal,e?.signal]);ie(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Cn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ie(1/0,this.walkController.signal);let e=Kr([this.walkController.signal,this.shutdownController.signal]);ie(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=rt(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await pr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Xl=32,Zl=64,Wi=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new x(`No handler registered for protocol ${e}`,k.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new x(`Handler already registered for protocol ${e}`,k.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=vi.bind({ignoreUndefined:!0})({maxInboundStreams:Xl,maxOutboundStreams:Zl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new x("invalid topology",k.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==k.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Ql=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function rp(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ql({name:e,metrics:t}):n=new Map,n}var Xi=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=rp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??zt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new x("Transport must have a valid tag",k.ERR_INVALID_KEY);if(this.transports.has(t))throw new x(`There is already a transport with the tag ${t}`,k.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new x(`No transport available for address ${String(e)}`,k.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new he("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=k.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new x("Not started",k.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==zt.NO_FATAL)throw new x(`Transport (${n}) could not listen on any available address`,k.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===zt.FATAL_ALL)throw new x(n,k.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var ke="/multistream/1.0.0";var Zi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,e={}){let t=$i(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??De;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Zi("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ji("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Qi("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var Gw=L(`
|
|
8
|
-
`)
|
|
9
|
-
`),i=
|
|
10
|
-
`)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`),
|
|
14
|
-
`),
|
|
15
|
-
`)
|
|
16
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',
|
|
17
|
-
`)
|
|
18
|
-
`))),
|
|
19
|
-
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Hr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Hr(n,L(`na
|
|
20
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var Qw=500,ru=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[hu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new x("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new x("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new x("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Qw);ie(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function sp(r){return new ru(r)}var Jw=3e4;function eb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Xl}function tb(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Zl}function ip(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var ia=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new x(`The multiaddr connection is blocked by gater.${n}`,k.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new x("connection denied",k.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new x("inbound upgrade timeout",Po))};u.addEventListener("abort",f,{once:!0}),ie(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new x("The multiaddr connection is blocked by gater.acceptConnection",k.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the inbound connection"),l=await d.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new he("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new x("inbound connection that skipped encryption must have a peer id",k.ERR_INVALID_MULTIADDR);let h=ye(d);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new he("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.muxers);a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new x("Encryption was skipped but no peer id was passed",k.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await Co(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=eb(y,this.components.registrar);if(ip(y,"inbound",l)===b){let E=new x(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`,k.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(E),E}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new x("Stream is not multiplexed",k.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(Jw);ie(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await To(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=tb(b,this.components.registrar,m),E=ip(b,"outbound",l);if(E>=w){let A=new x(`Too many outbound protocol streams for protocol "${b}" - ${E}/${w}`,k.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y.code!=null?y:new x(String(y),k.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new x("connection is not multiplexed",k.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=sp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new x("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Co(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new x(n.message,k.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await To(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new x(o.message,k.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await To(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new x(String(o),k.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Co(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new x(String(o),k.ERR_MUXER_UNAVAILABLE)}}};var ap="1.9.3-dd7b329c4",cp="libp2p";var nu=class extends St{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new St,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new fa(a.type,{detail:a.detail}));return c||u},ie(1/0,t),this.peerId=e.peerId,this.logger=e.logger??zs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Ed({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:cp,version:ap},logger:this.logger,events:t,datastore:e.datastore??new li,connectionGater:Ad(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new ai(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new ia(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Xi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Vi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new qi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Wi(this.components)),this.configureComponent("addressManager",new ui(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Yi(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new zi(this.components,{routers:i})),this.configureComponent("randomWalk",new ji(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[ca]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ca])),u[ua]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ua])),u[la]!=null&&(this.log("registering service %s for peer discovery",a),u[la].addEventListener?.("peer",f=>{this.#e(f)}))}xd(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Kt;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new x("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new x("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ur(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==k.ERR_NOT_FOUND)throw s}let n=Ie([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return ao(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(k.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function lp(r={}){let e=r.peerId??=await Uh();if(e.privateKey==null)throw new x("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await co(e.privateKey),new nu(await jd(r))}async function nb(r={}){let e=await lp(r);return r.start!==!1&&await e.start(),e}return _p(ob);})();
|
|
6
|
+
`)}`:`${t} :`}};zf=Yt;C.Constructed=zf;Yt.NAME="CONSTRUCTED";var ws=class extends Le{fromBER(e,t,n){return t}toBER(e){return at}};ws.override="EndOfContentValueBlock";var Gf,bs=class extends Ae{constructor(e={}){super(e,ws),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Gf=bs;C.EndOfContent=Gf;bs.NAME=qn;var Wf,Jr=class extends Ae{constructor(e={}){super(e,Le),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Wf=Jr;C.Null=Wf;Jr.NAME="NULL";var xs=class extends Rt(Le){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Pt(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Gc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};xs.NAME="BooleanValueBlock";var jf,vs=class extends Ae{constructor(e={}){super(e,xs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};jf=vs;C.Boolean=jf;vs.NAME="BOOLEAN";var Es=class extends Rt(dt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=dt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Hf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?dt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Es.NAME="OctetStringValueBlock";var Zf,As=class r extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Es),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ys(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Yt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};Zf=As;C.OctetString=Zf;As.NAME=Hf;var Ss=class extends Rt(dt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=dt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==$f)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ys(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return dt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return at;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}}};Ss.NAME="BitStringValueBlock";var Xf,Qr=class extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Yt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Xf=Qr;C.BitString=Xf;Qr.NAME=$f;var Yf;function k0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=fs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=fs(t,s)),s}function Vf(r){if(r>=$n.length)for(let e=$n.length;e<=r;e++){let t=new Uint8Array([0]),n=$n[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=fs(t,n)),$n.push(n)}return $n[r]}function I0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var zn=class extends Rt(Le){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Gc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Uf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=I0(Vf(n),t),i="-";break;default:t=k0(t,Vf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Ff.charAt(t[c]));return a===!1&&(i+=Ff.charAt(0)),i}};Yf=zn;zn.NAME="IntegerValueBlock";Object.defineProperty(Yf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Jf,Se=class r extends Ae{constructor(e={}){super(e,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return hs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){hs();let t=BigInt(e),n=new Kn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Jf=Se;C.Integer=Jf;Se.NAME="INTEGER";var Qf,_s=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Qf=_s;C.Enumerated=Qf;_s.NAME="ENUMERATED";var Gn=class extends Rt(Le){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){hs();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Xt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",at;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Gn.NAME="sidBlock";var Bs=class extends Le{constructor({value:e=tn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Gn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,at;t.push(o)}return Wc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Gn;if(o>Number.MAX_SAFE_INTEGER){hs();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Bs.NAME="ObjectIdentifierValueBlock";var eh,en=class extends Ae{constructor(e={}){super(e,Bs),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};eh=en;C.ObjectIdentifier=eh;en.NAME="OBJECT IDENTIFIER";var Wn=class extends Rt(Tt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Xt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",at;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Wn.NAME="relativeSidBlock";var ks=class extends Le{constructor({value:e=tn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,at;n.push(s)}return Wc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Wn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ks.NAME="RelativeObjectIdentifierValueBlock";var th,Is=class extends Ae{constructor(e={}){super(e,ks),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};th=Is;C.RelativeObjectIdentifier=th;Is.NAME="RelativeObjectIdentifier";var rh,Lt=class extends Yt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};rh=Lt;C.Sequence=rh;Lt.NAME="SEQUENCE";var nh,Cs=class extends Yt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};nh=Cs;C.Set=nh;Cs.NAME="SET";var Ts=class extends Rt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=tn}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="StringValueBlock";var Ls=class extends Ts{};Ls.NAME="SimpleStringValueBlock";var Oe=class extends ms{constructor({...e}={}){super(e,Ls)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Oe.NAME="SIMPLE STRING";var Ns=class extends Oe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ns.NAME="Utf8StringValueBlock";var oh,Nt=class extends Ns{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};oh=Nt;C.Utf8String=oh;Nt.NAME="UTF8String";var Ps=class extends Oe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ps.NAME="BmpStringValueBlock";var sh,Rs=class extends Ps{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};sh=Rs;C.BmpString=sh;Rs.NAME="BMPString";var Ds=class extends Oe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Xt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Ds.NAME="UniversalStringValueBlock";var ih,Ms=class extends Ds{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ih=Ms;C.UniversalString=ih;Ms.NAME="UniversalString";var ah,Us=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ah=Us;C.NumericString=ah;Us.NAME="NumericString";var ch,Os=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};ch=Os;C.PrintableString=ch;Os.NAME="PrintableString";var lh,Fs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};lh=Fs;C.TeletexString=lh;Fs.NAME="TeletexString";var uh,Vs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};uh=Vs;C.VideotexString=uh;Vs.NAME="VideotexString";var fh,Hs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};fh=Hs;C.IA5String=fh;Hs.NAME="IA5String";var hh,$s=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};hh=$s;C.GraphicString=hh;$s.NAME="GraphicString";var dh,jn=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};dh=jn;C.VisibleString=dh;jn.NAME="VisibleString";var ph,Ks=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ph=Ks;C.GeneralString=ph;Ks.NAME="GeneralString";var mh,qs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};mh=qs;C.CharacterString=mh;qs.NAME="CharacterString";var gh,Zn=class extends jn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};gh=Zn;C.UTCTime=gh;Zn.NAME="UTCTime";var yh,zs=class extends Zn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};yh=zs;C.GeneralizedTime=yh;zs.NAME="GeneralizedTime";var wh,Gs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};wh=Gs;C.DATE=wh;Gs.NAME="DATE";var bh,Ws=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};bh=Ws;C.TimeOfDay=bh;Ws.NAME="TimeOfDay";var xh,js=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};xh=js;C.DateTime=xh;js.NAME="DateTime";var vh,Zs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};vh=Zs;C.Duration=vh;Zs.NAME="Duration";var Eh,Xs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Eh=Xs;C.TIME=Eh;Xs.NAME="TIME";function H(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function rn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return zr(r)}var Xn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Yn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Js=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ah={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Js("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Jt=Ah;async function Sh(r){let e=await Jt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await T0(e);return{privateKey:t[0],publicKey:t[1]}}async function _h(r,e){let t=await Jt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Jt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Bh(r,e,t){let n=await Jt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Jt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function T0(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([Jt.get().subtle.exportKey("jwk",r.privateKey),Jt.get().subtle.exportKey("jwk",r.publicKey)])}function Xc(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 nn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return Bh(this._key,t,e)}},Qn=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return _h(this._key,e)}};var Qs=8192,Yc=18;function kh(r){let{result:e}=Zc(r),t=e.valueBlock.value;return{n:H(pt(t[1].toBigInt()),"base64url"),e:H(pt(t[2].toBigInt()),"base64url"),d:H(pt(t[3].toBigInt()),"base64url"),p:H(pt(t[4].toBigInt()),"base64url"),q:H(pt(t[5].toBigInt()),"base64url"),dp:H(pt(t[6].toBigInt()),"base64url"),dq:H(pt(t[7].toBigInt()),"base64url"),qi:H(pt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function L0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new D("JWK was missing components");let t=new Lt({value:[new Se({value:0}),Se.fromBigInt(mt(P(r.n,"base64url"))),Se.fromBigInt(mt(P(r.e,"base64url"))),Se.fromBigInt(mt(P(r.d,"base64url"))),Se.fromBigInt(mt(P(r.p,"base64url"))),Se.fromBigInt(mt(P(r.q,"base64url"))),Se.fromBigInt(mt(P(r.dp,"base64url"))),Se.fromBigInt(mt(P(r.dq,"base64url"))),Se.fromBigInt(mt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Ih(r){let{result:e}=Zc(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(pt(t[0].toBigInt()),"base64url"),e:H(pt(t[1].toBigInt()),"base64url")}}function Jc(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Lt({value:[new Lt({value:[new en({value:"1.2.840.113549.1.1.1"}),new Jr]}),new Qr({valueHex:new Lt({value:[Se.fromBigInt(mt(P(r.n,"base64url"))),Se.fromBigInt(mt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function pt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function mt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function Ch(r){let e=kh(r);return Th(e)}function Qc(r){let e=Ih(r);if(Xc(e)>Qs)throw new Pr("Key size is too large");let t=Xr(ht.encode({Type:ge.RSA,Data:r})),n=et(Yc,t);return new nn(e,n)}function Th(r){if(Xc(r)>Qs)throw new D("Key size is too large");let e=Lh(r),t=Xr(ht.encode({Type:ge.RSA,Data:Jc(e.publicKey)})),n=et(Yc,t);return new Qn(e.privateKey,new nn(e.publicKey,n))}async function el(r){if(r>Qs)throw new D("Key size is too large");let e=await Sh(r),t=Xr(ht.encode({Type:ge.RSA,Data:Jc(e.publicKey)})),n=et(Yc,t);return new Qn(e.privateKey,new nn(e.publicKey,n))}function Lh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ei=class extends qr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ju(e);let n=Nn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),$r(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tl=(r,e,t)=>new ei(r,e).update(t).digest();tl.create=(r,e)=>new ei(r,e);function Nh(r){r.lowS!==void 0&&nt("lowS",r.lowS),r.prehash!==void 0&&nt("prehash",r.prehash)}function N0(r){let e=Dn(r);ut(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:P0,hexToBytes:R0}=Xo,Dt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Dt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=ar(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?ar(o.length/2|128):"";return`${ar(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Dt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Dt;if(r<Mt)throw new e("integer: negative integers are not allowed");let t=ar(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Dt;if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return P0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Dt,o=typeof r=="string"?R0(r):r;Wr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Dt,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Mt=BigInt(0),ve=BigInt(1),Yv=BigInt(2),Ph=BigInt(3),Jv=BigInt(4);function D0(r){let e=N0(r),{Fp:t}=e,n=Gt(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return It(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Pn(m,ve,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(Kt(m)&&(m=Bt(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:kt(ae("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=Y(x,w)),$e("private key",x,ve,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=ur((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let A=t.mul(y,g),_=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=ur(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(ae("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Qo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(y,_),t.mul(x,w)),B=t.eql(t.mul(b,_),t.mul(A,w));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,Ph),{px:w,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,T=t.mul(w,w),ee=t.mul(x,x),V=t.mul(A,A),F=t.mul(w,x);return F=t.add(F,F),B=t.mul(w,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,V),v=t.add(_,v),_=t.sub(ee,v),v=t.add(ee,v),v=t.mul(_,v),_=t.mul(F,_),B=t.mul(b,B),V=t.mul(g,V),F=t.sub(T,V),F=t.mul(g,F),F=t.add(F,B),B=t.add(T,T),T=t.add(B,T),T=t.add(T,V),T=t.mul(T,F),v=t.add(v,T),V=t.mul(x,A),V=t.add(V,V),T=t.mul(V,F),_=t.sub(_,T),B=t.mul(V,ee),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,T=t.ZERO,ee=e.a,V=t.mul(e.b,Ph),F=t.mul(y,x),R=t.mul(b,A),I=t.mul(w,_),L=t.add(y,b),S=t.add(x,A);L=t.mul(L,S),S=t.add(F,R),L=t.sub(L,S),S=t.add(y,w);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(F,I),S=t.sub(S,E),E=t.add(b,w),v=t.add(A,_),E=t.mul(E,v),v=t.add(R,I),E=t.sub(E,v),T=t.mul(ee,S),v=t.mul(V,I),T=t.add(v,T),v=t.sub(R,T),T=t.add(R,T),B=t.mul(v,T),R=t.add(F,F),R=t.add(R,F),I=t.mul(ee,I),S=t.mul(V,S),R=t.add(R,I),I=t.sub(F,I),I=t.mul(ee,I),S=t.add(S,I),F=t.mul(R,S),B=t.add(B,F),F=t.mul(E,S),v=t.mul(L,v),v=t.sub(v,F),F=t.mul(L,R),T=t.mul(E,T),T=t.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$e("scalar",g,Mt,e.n);let y=d.ZERO;if(g===Mt)return y;if(g===ve)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Mt||_>Mt;)x&ve&&(v=v.add(T)),_&ve&&(B=B.add(T)),T=T.double(),x>>=ve,_>>=ve;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(t.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=e;$e("scalar",g,ve,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:ee}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(t.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=ee.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Mt||v===ve||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===ve)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===ve?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return nt("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return nt("isCompressed",g),Bt(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Jo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function M0(r){let e=Dn(r);return ut(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Rh(r){let e=M0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Y(I,n)}function a(I){return Yo(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=D0({...e,toBytes(I,L,S){let E=L.toAffine(),k=t.toBytes(E.x),N=It;return nt("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),k):N(Uint8Array.from([4]),k,t.toBytes(E.y))},fromBytes(I){let L=I.length,S=I[0],E=I.subarray(1);if(L===o&&(S===2||S===3)){let k=kt(E);if(!Pn(k,ve,t.ORDER))throw new Error("Point is not on curve");let N=f(k),M;try{M=t.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&ve)===ve;return(S&1)===1!==U&&(M=t.neg(M)),{x:k,y:M}}else if(L===s&&S===4){let k=t.fromBytes(E.subarray(0,t.BYTES)),N=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:k,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=I=>Bt(zt(I,e.nByteLength));function h(I){let L=n>>ve;return I>L}function p(I){return h(I)?i(-I):I}let m=(I,L,S)=>kt(I.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=e.nByteLength;return L=ae("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=Dt.toSig(ae("DER",L));return new g(S,E)}assertValidity(){$e("r",this.r,ve,n),$e("s",this.s,ve,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:k}=this,N=_(ae("msgHash",L));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let M=k===2||k===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=k&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),X=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,X);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return cr(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return cr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let I=oc(e.n);return hf(e.randomBytes(I),e.n)},precompute(I=8,L=c.BASE){return L._setWindowSize(I),L.multiply(BigInt(3)),L}};function b(I,L=!0){return c.fromPrivateKey(I).toRawBytes(L)}function w(I){let L=Kt(I),S=typeof I=="string",E=(L||S)&&I.length;return L?E===o||E===s:S?E===2*o||E===2*s:I instanceof c}function x(I,L,S=!0){if(w(I))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(I)).toRawBytes(S)}let A=e.bits2int||function(I){let L=kt(I),S=I.length*8-e.nBitLength;return S>0?L>>BigInt(S):L},_=e.bits2int_modN||function(I){return i(A(I))},v=Rn(e.nBitLength);function B(I){return $e(`num < 2^${e.nBitLength}`,I,Mt,v),zt(I,e.nByteLength)}function T(I,L,S=ee){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:k}=e,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),I=ae("msgHash",I),Nh(S),M&&(I=ae("prehashed msgHash",E(I)));let $=_(I),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let xe=U===!0?k(t.BYTES):U;K.push(ae("extraEntropy",xe))}let X=It(...K),Q=$;function be(xe){let Ee=A(xe);if(!l(Ee))return;let Pe=a(Ee),de=c.BASE.multiply(Ee).toAffine(),He=i(de.x);if(He===Mt)return;let wt=i(Pe*i(Q+He*z));if(wt===Mt)return;let Sn=(de.x===He?0:2)|Number(de.y&ve),_n=wt;return N&&h(wt)&&(_n=p(wt),Sn^=1),new g(He,_n,Sn)}return{seed:X,k2sig:be}}let ee={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function F(I,L,S=ee){let{seed:E,k2sig:k}=T(I,L,S),N=e;return ec(N.hash.outputLen,N.nByteLength,N.hmac)(E,k)}c.BASE._setWindowSize(8);function R(I,L,S,E=V){let k=I;if(L=ae("msgHash",L),S=ae("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");Nh(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof k=="string"||Kt(k))try{U=g.fromDER(k)}catch(de){if(!(de instanceof Dt.Err))throw de;U=g.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:de,s:He}=k;U=new g(de,He)}else throw new Error("PARSE");$=c.fromHex(S)}catch(de){if(de.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=e.hash(L));let{r:z,s:K}=U,X=_(L),Q=a(K),be=i(X*Q),xe=i(z*Q),Ee=c.BASE.multiplyAndAddUnsafe($,be,xe)?.toAffine();return Ee?i(Ee.x)===z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function U0(r){return{hash:r,hmac:(e,...t)=>tl(r,e,Ga(...t)),randomBytes:zr}}function Dh(r,e){let t=n=>Rh({...r,...U0(n)});return Object.freeze({...t(e),create:t})}var Oh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Mh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),O0=BigInt(1),rl=BigInt(2),Uh=(r,e)=>(r+e/rl)/e;function F0(r){let e=Oh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=re(f,t,e)*f%e,d=re(l,t,e)*f%e,h=re(d,rl,e)*u%e,p=re(h,o,e)*h%e,m=re(p,s,e)*p%e,g=re(m,a,e)*m%e,y=re(g,c,e)*g%e,b=re(y,a,e)*m%e,w=re(b,t,e)*f%e,x=re(w,i,e)*p%e,A=re(x,n,e)*u%e,_=re(A,rl,e);if(!nl.eql(nl.sqr(_),r))throw new Error("Cannot find square root");return _}var nl=Gt(Oh,void 0,void 0,{sqrt:F0}),Xe=Dh({a:BigInt(0),b:BigInt(7),Fp:nl,n:Mh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Mh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-O0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Uh(s*r,e),c=Uh(-n*r,e),u=Y(r-a*t-c*o,e),f=Y(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Xr),a2=BigInt(0);var c2=Xe.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ke(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ol(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Fh(r,e){let t=jr.digest(e instanceof Uint8Array?e:e.subarray());if(ol(t))return t.then(({digest:n})=>Xe.sign(n,r).toDERRawBytes()).catch(n=>{throw new Xn(String(n))});try{return Xe.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Xn(String(n))}}function Vh(r,e,t){let n=jr.digest(t instanceof Uint8Array?t:t.subarray());if(ol(n))return n.then(({digest:o})=>Xe.verify(e,o,r)).catch(o=>{throw new Yn(String(o))});try{return Xe.verify(e,n.digest,r)}catch(o){throw new Yn(String(o))}}var eo=class{type="secp256k1";raw;_key;constructor(e){this._key=Kh(e),this.raw=Hh(this._key)}toMultihash(){return St.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return Vh(this._key,t,e)}},ti=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=$h(e),this.publicKey=new eo(t??qh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return Fh(this.raw,e)}};function sl(r){return new eo(r)}async function zh(){let r=V0();return new ti(r)}function Hh(r){return Xe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function $h(r){try{return Xe.getPublicKey(r,!0),r}catch(e){throw new Bn(String(e))}}function Kh(r){try{return Xe.ProjectivePoint.fromHex(r),r}catch(e){throw new Pr(String(e))}}function qh(r){try{return Xe.getPublicKey(r,!0)}catch(e){throw new Bn(String(e))}}function V0(){return Xe.utils.randomPrivateKey()}async function Gh(r,e){if(r==="Ed25519")return vf();if(r==="secp256k1")return zh();if(r==="RSA")return el(e??2048);throw new Ft}function on(r){let{Type:e,Data:t}=ht.decode(r),n=t??new Uint8Array;switch(e){case ge.RSA:return Qc(n);case ge.Ed25519:return lc(n);case ge.secp256k1:return sl(n);default:throw new Ft}}function Wh(r){let{Type:e,Data:t}=ht.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return lc(n);case ge.secp256k1:return sl(n);default:throw new Ft}}function ft(r){return ht.encode({Type:ge[r.type],Data:r.raw})}var jh=Symbol.for("nodejs.util.inspect.custom"),H0=114,to=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Po]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(H0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[jh](){return`PeerId(${this.toString()})`}},ro=class extends to{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},no=class extends to{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},oo=class extends to{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$0=2336,so=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=St.digest(P(this.url))}[jh](){return`PeerId(${this.url})`}[Po]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1($0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var K0=114,Zh=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=tt(W.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=tt(e.decode(r))}return sn(t)}function il(r){if(r.type==="Ed25519")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ro({multihash:r.toCID().multihash,publicKey:r});throw new Ft}function Xh(r){return il(r.publicKey)}function sn(r){if(z0(r))return new ro({multihash:r});if(q0(r))try{let e=Wh(r);if(e.type==="Ed25519")return new no({multihash:r,publicKey:e});if(e.type==="secp256k1")return new oo({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new so(new URL(t))}throw new Vo("Supplied PeerID Multihash is invalid")}function ri(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==K0&&r.code!==Zh)throw new Fo("Supplied PeerID CID is invalid");if(r.code===Zh){let e=H(r.multihash.digest);return new so(new URL(e))}return sn(r.multihash)}function q0(r){return r.code===St.code}function z0(r){return r.code===jr.code}var ni=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Yh=45,G0=15,an=new ni;function al(r){if(!(r.length>G0))return an.new(r).parseWith(()=>an.readIPv4Addr())}function cl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Yh))return an.new(r).parseWith(()=>an.readIPv6Addr())}function oi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Yh))return an.new(r).parseWith(()=>an.readIPAddr())}function cn(r){return!!al(r)}function ln(r){return!!cl(r)}function si(r){return!!oi(r)}var yE=parseInt("0xFFFF",16),wE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ed=cn,Y0=ln,ll=function(r){let e=0;if(r=r.toString().trim(),ed(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Y0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ed(t[n]),i;s&&(i=ll(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},td=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var un={},ul={},Q0=[[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"]];Q0.forEach(r=>{let e=ey(...r);ul[e.code]=e,un[e.name]=e});function ey(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(ul[r]!=null)return ul[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(un[r]!=null)return un[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var QE=Z("ip4"),eA=Z("ip6"),tA=Z("ipcidr");function pl(r,e){switch(Z(r).code){case 4:case 41:return ry(e);case 42:return dl(e);case 6:case 273:case 33:case 132:return od(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dl(e);case 421:return iy(e);case 444:return nd(e);case 445:return nd(e);case 466:return sy(e);case 481:return globalThis.encodeURIComponent(dl(e));default:return H(e,"base16")}}function ml(r,e){switch(Z(r).code){case 4:return rd(e);case 41:return rd(e);case 42:return hl(e);case 6:case 273:case 33:case 132:return gl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hl(e);case 421:return ny(e);case 444:return ay(e);case 445:return cy(e);case 466:return oy(e);case 481:return hl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var fl=Object.values(On).map(r=>r.decoder),ty=function(){let r=fl[0].or(fl[1]);return fl.slice(2).forEach(e=>r=r.or(e)),r}();function rd(r){if(!si(r))throw new Error("invalid ip address");return ll(r)}function ry(r){let e=td(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!si(e))throw new Error("invalid ip address");return e}function gl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function od(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hl(r){let e=P(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function dl(r){let e=st(r);if(r=r.slice(he(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function ny(r){let e;r[0]==="Q"||r[0]==="1"?e=tt(W.decode(`z${r}`)).bytes:e=pe.parse(r).multihash.bytes;let t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function oy(r){let e=ty.decode(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function sy(r){let e=st(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function iy(r){let e=st(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function ay(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ze.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=gl(n);return Fe([t,o],t.length+o.length)}function cy(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ze.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=gl(n);return Fe([t,o],t.length+o.length)}function nd(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=od(t);return`${n}:${o}`}function sd(r){r=yl(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Z(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw ad("invalid address: "+r);if(a.path===!0){n=yl(o.slice(s).join("/")),e.push([a.code,ml(a.code,n)]),t.push([a.code,n]);break}let c=ml(a.code,o[s]);e.push([a.code,c]),t.push([a.code,pl(a.code,c)])}return{string:id(t),bytes:bl(e),tuples:e,stringTuples:t,path:n}}function wl(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=st(r,o),i=he(s),a=Z(s),c=ly(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw ad("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=pl(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:id(t),tuples:e,stringTuples:t,path:n}}function id(r){let e=[];return r.map(t=>{let n=Z(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),yl(e.join("/"))}function bl(r){return Fe(r.map(e=>{let t=Z(e[0]),n=Uint8Array.from(Ce(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function ly(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=st(e instanceof Uint8Array?e:Uint8Array.from(e));return t+he(t)}}function yl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ad(r){return new Error("Error parsing address: "+r)}var uy=Symbol.for("nodejs.util.inspect.custom"),xl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),fy=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],ii=class r{bytes;#e;#t;#s;#a;[xl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=wl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=sd(e)}else if(Qt(e))t=wl(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),fy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=Z(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=Z(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},Z(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Z(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(bl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===un.p2p.code&&e.push([n,o]),n===un["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(pe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=fn.get(t.name);if(n==null)throw new Nr(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>ne(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[uy](){return`Multiaddr(${this.#e})`}};var fn=new Map;function Qt(r){return!!r?.[xl]}function ne(r){return new ii(r)}var hy=r=>r.toString().split("/").slice(1),io=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),G=r=>({match:e=>io(t=>t===r).match(e),pattern:r}),li=()=>({match:r=>io(e=>typeof e=="string").match(r),pattern:"{string}"}),ui=()=>({match:r=>io(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),_e=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ai=()=>({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}"}),ye=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ye=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),J=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ue(...r){function e(o){let s=hy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var El=J(G("dns4"),li()),Al=J(G("dns6"),li()),Sl=J(G("dnsaddr"),li()),cd=J(G("dns"),li()),TA=ue(El),LA=ue(Al),NA=ue(Sl),PA=ue(Ye(cd,Sl,El,Al)),ld=J(G("ip4"),io(cn)),ud=J(G("ip6"),io(ln)),fd=Ye(ld,ud),yt=Ye(fd,cd,El,Al,Sl),RA=ue(yt),DA=ue(ld),MA=ue(ud),UA=ue(fd),_l=J(yt,G("tcp"),ui()),ao=J(yt,G("udp"),ui()),OA=ue(_l),FA=ue(ao),Bl=J(ao,G("quic")),fi=J(ao,G("quic-v1")),dy=Ye(Bl,fi),VA=ue(Bl),HA=ue(fi),vl=Ye(yt,_l,ao,Bl,fi),hd=Ye(J(vl,G("ws"),ye(_e()))),$A=ue(hd),dd=Ye(J(vl,G("wss"),ye(_e())),J(vl,G("tls"),G("ws"),ye(_e()))),KA=ue(dd),pd=J(ao,G("webrtc-direct"),ye(ai()),ye(ai()),ye(_e())),qA=ue(pd),md=J(fi,G("webtransport"),ye(ai()),ye(ai()),ye(_e())),zA=ue(md),ci=Ye(hd,dd,J(_l,ye(_e())),J(dy,ye(_e())),J(yt,ye(_e())),pd,md,_e()),GA=ue(ci),py=J(ci,G("p2p-circuit"),_e()),co=ue(py),my=Ye(J(ci,G("p2p-circuit"),G("webrtc"),ye(_e())),J(ci,G("webrtc"),ye(_e())),G("webrtc")),WA=ue(my),gy=Ye(J(yt,G("tcp"),ui(),G("http"),ye(_e())),J(yt,G("http"),ye(_e()))),jA=ue(gy),yy=Ye(J(yt,G("tcp"),Ye(J(G("443"),G("http")),J(ui(),G("https"))),ye(_e())),J(yt,G("tls"),G("http"),ye(_e())),J(yt,G("https"),ye(_e()))),ZA=ue(yy);var yd=sr(gd(),1),wy=["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"],by=wy.map(r=>new yd.Netmask(r));function kl(r){for(let e of by)if(e.contains(r))return!0;return!1}function xy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function vy(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return kl(o)}function Ey(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ay(r){let e=r.split(":"),t=e[e.length-1];return kl(t)}function Sy(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 hi(r){return cn(r)?kl(r):xy(r)?vy(r):Ey(r)?Ay(r):ln(r)?Sy(r):void 0}function Il(r){try{let{address:e}=r.nodeAddress();return!!hi(e)}catch{return!0}}function _y(r,e){let t=Il(r.multiaddr),n=Il(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function By(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function ky(r,e){let t=co.exactMatch(r.multiaddr),n=co.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function hn(r,e){let t=_y(r,e);if(t!==0)return t;let n=ky(r,e);return n!==0?n:By(r,e)}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Tl=sr(bd(),1);var fo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ll=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xd=r=>globalThis.DOMException===void 0?new Ll(r):new DOMException(r),vd=r=>{let e=r.reason===void 0?xd("This operation was aborted."):r.reason;return e instanceof Error?e:xd(e)};function ho(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&f(vd(d)),d.addEventListener("abort",()=>{f(vd(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new fo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Nl(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var po=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Nl(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var er=class extends Tl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:po,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#x){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=ho(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof fo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};function pi(r){let e=[We.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Pl=60;function mi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:We[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:We[e.type],TTL:e.TTL??e.ttl??Pl,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var Ty=4;function Rl(r,e={}){let t=new er({concurrency:e.queryConcurrency??Ty});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(o.types).forEach(a=>{s.append("type",We[a])}),o.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=mi(await a.json());return o.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ed(){return[Rl("https://cloudflare-dns.com/dns-query"),Rl("https://dns.google/resolve")]}var _d=sr(Sd(),1);var Dl=class{lru;constructor(e){this.lru=(0,_d.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return mi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:We[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Pl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Bd(r){return new Dl(r)}var Ly=1e3,gi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Bd(e.cacheSize??Ly),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ed())}async query(e,t={}){let n=pi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new fe("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new fe("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var We;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(We||(We={}));function kd(r={}){return new gi(r)}var Ny=32,{code:Py}=Z("dnsaddr"),yr=async function(e,t={}){let n=t.maxRecursiveDepth??Ny;if(n===0)throw new Nr("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===Py)??[],i=await(t?.dns??kd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[We.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ne(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Md=sr(Dd(),1),bi=Md.default;var Fy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:yr},addressSorter:hn},transportManager:{faultTolerance:Ot.FATAL_ALL}};async function Ud(r){let e=bi(Fy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function Vy(r,e){try{if(typeof r=="string"&&r.length>0)return Hy(r);if(typeof r=="number"&&isFinite(r))return e?.long?Ky(r):$y(r);throw new Error("Value is not a string or number.")}catch(t){let n=qy(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Hy(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var vi=Vy;function $y(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Ky(r){let e=Math.abs(r);return e>=864e5?xi(r,e,864e5,"day"):e>=36e5?xi(r,e,36e5,"hour"):e>=6e4?xi(r,e,6e4,"minute"):e>=1e3?xi(r,e,1e3,"second"):`${r} ms`}function xi(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function qy(r){return typeof r=="object"&&r!==null&&"message"in r}function Ul(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=vi,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=t.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Ei=Yy(),zy=["#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 Gy(){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 Wy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vi(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var jy=console.debug??console.log??(()=>{});function Zy(r){try{r?Ei?.setItem("debug",r):Ei?.removeItem("debug")}catch{}}function Xy(){let r;try{r=Ei?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Yy(){try{return localStorage}catch{}}function Jy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Od=Ul({formatArgs:Wy,save:Zy,load:Xy,useColors:Gy,setupFormatters:Jy,colors:zy,storage:Ei,log:jy});var je=Od;je.formatters.b=r=>r==null?"undefined":W.baseEncode(r);je.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);je.formatters.m=r=>r==null?"undefined":Bc.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function Qy(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ai(){return{forComponent(r){return ew(r)}}}function ew(r){let e=Qy(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=je(`${r}:trace`)),Object.assign(je(r),{error:je(`${r}:error`),trace:e})}function wr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Si(r){let e=tt(W.decode(`z${r}`));return sn(e)}var ct=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return wr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return wr(this.map.values(),e=>e.key)}values(){return wr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return wr(this.set.entries(),e=>{let t=Si(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Si(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return wr(this.set.values(),e=>Si(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Kd=Symbol.for("@achingbrain/uint8arraylist");function $d(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Bi(r){return!!r?.[Kd]}var we=class r{bufs;length;[Kd]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Bi(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Bi(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=$d(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$d(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Bi(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Bi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Ol=64,lt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Ol)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ie(this.fp,e.fp):!1}};function xr(r,e){return Math.floor(Math.random()*(e-r))+r}var vr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=xr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Fl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},zd=new globalThis.TextEncoder;function tw(r,e){let t=Fl[e],n=qd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function rw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fl[e],o=qd[e],s=r;for(;s.length>0;){let i=zd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Vl(r,{size:e=32,utf8Buffer:t}={}){if(!Fl[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return rw(r,e,t);r=zd.encode(r)}return tw(r,e)}var nw=sr(Hd(),1);var go={hash:r=>Number(Vl(r,{size:32})),hashV:(r,e)=>ow(go.hash(r,e))};function ow(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var sw=500,yo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??go,this.seed=e.seed??xr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new vr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[xr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new vr(this.bucketSize));for(let a=0;a<sw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new vr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},iw={1:.5,2:.84,4:.95,8:.98};function aw(r=.001){return r>.002?2:r>1e-5?4:8}function Gd(r,e=.001){let t=aw(e),n=iw[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Ol);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ki=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??go,this.seed=e.seed??xr(0,Math.pow(2,10)),this.filterSeries=[new yo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new yo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Hl(r,e=.001,t){return new ki({...Gd(r,e),...t??{}})}var wo;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(wo||(wo={}));var Ii=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async e=>{let t=wo.decode(e),n=on(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Wd(n,o,s),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ii("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=wo.encode({publicKey:ft(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=Wd(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Wd=(r,e,t)=>{let n=P(r),o=Ce(n.byteLength),s=Ce(e.length),i=Ce(t.length);return new we(o,n,s,e,i,t)};function jd(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Zd="libp2p-peer-record",Xd=Uint8Array.from([3,1]);var bo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Me(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(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 mr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(bo||(bo={}));var Er=class r{static createFromProtobuf=e=>{let t=bo.decode(e),n=sn(tt(t.peerId)),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Xd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=bo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!jd(this.multiaddrs,e.multiaddrs))}};function cw(r){return r[Symbol.asyncIterator]!=null}function lw(r){if(cw(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var xo=lw;var tr={},gn=r=>{r.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)})};gn.addEventListener=(r,e)=>{tr[r]==null&&(tr[r]=[]),tr[r].push(e)};gn.removeEventListener=(r,e)=>{tr[r]!=null&&(tr[r]=tr[r].filter(t=>t===e))};gn.dispatchEvent=function(r,e,t){tr[r]!=null&&tr[r].forEach(n=>n(e,t))};var $l=gn;var Kl="lock:worker:request-read",ql="lock:worker:release-read",zl="lock:master:grant-read",Gl="lock:worker:request-write",Wl="lock:worker:release-write",jl="lock:master:grant-write";var Yd=(r=21)=>Math.random().toString().substring(2);var Jd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Qd=(r,e,t,n)=>async()=>{let o=Yd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},uw={singleProcess:!1},ep=r=>{if(r=Object.assign({},uw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return $l.addEventListener("message",Jd(t,"requestReadLock",Kl,ql,zl)),$l.addEventListener("message",Jd(t,"requestWriteLock",Gl,Wl,jl)),t}return{isWorker:!0,readLock:t=>Qd(t,Kl,zl,ql),writeLock:t=>Qd(t,Gl,jl,Wl)}};var Ar={},rr;async function Zl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>ho((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var fw=(r,e)=>{if(rr.isWorker===!0)return{readLock:rr.readLock(r,e),writeLock:rr.writeLock(r,e)};let t=new er({concurrency:1}),n;return{async readLock(){if(n!=null)return Zl(n,e);n=new er({concurrency:e.concurrency,autoStart:!1});let o=n,s=Zl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Zl(t,e)}}},hw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Xl(r){let e=Object.assign({},hw,r);return rr==null&&(rr=ep(e),rr.isWorker!==!0&&(rr.addEventListener("requestReadLock",t=>{Ar[t.data.name]!=null&&Ar[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),rr.addEventListener("requestWriteLock",async t=>{Ar[t.data.name]!=null&&Ar[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Ar[e.name]==null&&(Ar[e.name]=fw(e.name,e)),Ar[e.name]}var yn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ti.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=Ti.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ci.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 mr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ci.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 mr('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 Hn('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 Hn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Me(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(yn||(yn={}));var Ci;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ci||(Ci={}));var Ti;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ti||(Ti={}));function wn(r,e){let t=yn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=on(t.publicKey);r=il(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ne(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ut="/",tp=new TextEncoder().encode(Ut),Li=tp[0],Sr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Li)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=tp),this._buf[0]!==Li){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Li,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Li;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ut).slice(1)}type(){return dw(this.baseNamespace())}name(){return pw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...mw(e.map(t=>t.namespaces()))])}};function dw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function pw(r){let e=r.split(":");return e[e.length-1]}function mw(r){return[].concat(...r)}var Yl="/peers/";function bn(r){if(!Ro(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Sr(`${Yl}${e}`)}async function rp(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ne(o.multiaddr)),!Qt(o.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Pi(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ni(d,{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ni(d,{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ni([...a.entries()],{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ni([...h.entries()],{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=ft(o.id.publicKey):e.publicKey!=null?f=ft(e.publicKey):r.publicKey!=null&&(f=ft(r.publicKey));let l={addresses:await rp(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 Ni(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function np(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function op(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function sp(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Ri(r,e,t){let n=r.toString().split("/")[2],o=pe.parse(n,ze),s=ri(o),i=t.get(s);if(i!=null)return i;let a=wn(s,e);return t.set(s,a),a}function gw(r,e){return r==null?{}:{prefix:Yl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ri(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ri(n.key,n.value,e),Ri(o.key,o.value,e)))}}var Di=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Xl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(bn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(bn(e))}async load(e){let t=await this.datastore.get(bn(e));return wn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new ct;for await(let{key:n,value:o}of this.datastore.query(gw(e??{},t))){let s=Ri(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(bn(e)),n=wn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let s=yn.encode(t);return n!=null&&ie(s,n)?{peer:wn(e,s),previous:o,updated:!1}:(await this.datastore.put(bn(e),s),{peer:wn(e,s),previous:o,updated:!0})}};var Mi=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Di(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await xo(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Er.DOMAIN),o=ri(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let s=Er.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 mn.createFromProtobuf(i.peerRecordEnvelope),c=Er.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};var Ui=class extends Error{constructor(e="Not Found"){super(e),this.name="NotFoundError"}};function yw(r){return r[Symbol.asyncIterator]!=null}function ww(r){if(yw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Jl=ww;function bw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ip=bw;function xw(r){return r[Symbol.asyncIterator]!=null}function vw(r,e){let t=0;if(xw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ip(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var _r=vw;function Ew(r){return r[Symbol.asyncIterator]!=null}function Aw(r,e){return Ew(r)?async function*(){yield*(await xo(r)).sort(e)}():function*(){yield*xo(r).sort(e)}()}var Ql=Aw;function Sw(r){return r[Symbol.asyncIterator]!=null}function _w(r,e){return Sw(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var eu=_w;var Oi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Jl(this.putMany(e,n)),e=[],await Jl(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=_r(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ql(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=_r(n,()=>o++>=s)}return e.limit!=null&&(n=eu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=_r(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ql(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=_r(n,()=>s++>=o)}return e.limit!=null&&(n=eu(n,e.limit)),n}};var Fi=class extends Oi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw new Ui;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Sr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Sr(e)}};function ap(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Bw=r=>r;function tu(r,e){let t=r.getPeerId();return t!=null&>(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var Vi=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Bw,this._updatePeerStoreAddresses=ap(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>ne(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>ne(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ne(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ne(e))}addObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>ne(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var cp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(cp||(cp={}));var Hi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},$i=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},vo=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Eo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Ki=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},qi=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},zi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ao=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Br=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},So=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Gi=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},kr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},_o=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Wi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var ru=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ai())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>qo(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Iw=["metrics","connectionProtector","dns"],Cw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function lp(r={}){let e=new ru(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Cw.includes(o)){let i=e.components[o];if(i==null&&!Iw.includes(o))throw new Hi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function up(r){let e={};for(let t of Object.values(r.components))for(let n of Tw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Lw(t))if(e[n]!==!0)throw new $i(`Service "${Nw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Tw(r){return Array.isArray(r?.[In])?r[In]:[]}function Lw(r){return Array.isArray(r?.[Ma])?r[Ma]:[]}function Nw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function fp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!hi(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var hp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Pw=new WeakMap;function Rw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(hp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(hp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Pw.set(l,()=>{c(s),s=null,i()}),l}}var Dw=Rw(),dp=Dw;var ji=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var Zi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new nu}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ji("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 dp(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},nu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function Xi(r){if(Ro(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:gt(t),r.forEach(n=>{if(!Qt(n))throw new Rr("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=gt(o);if(e?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function pp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Mw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var mp="last-dial-failure",gp="last-dial-success";var Yi=100,Ji=50;var yp={maxConnections:Yi,allow:[]},Qi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??yp.maxConnections,this.allow=t.allow??yp.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new ct;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await pp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ea=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},xn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ea(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ea(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ou=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ta(r={}){return Uw(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Uw(r,e){e=e??{};let t=e.onEnd,n=new xn,o,s,i,a=le(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=le()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new xn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new xn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new ou)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var su=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function vn(r,e,t,n){let o=new su(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ra=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function nr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ra(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ra(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var na=class{deferred;signal;constructor(e){this.signal=e,this.deferred=le(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ow(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var oa=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ow(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,oe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new bt),this.cleanup())}async join(e={}){let t=new na(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await nr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var En=class extends vt{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new oa(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new bt)}),this.clear()}async onEmpty(e){this.size!==0&&await vn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await vn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await vn(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ta({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new bt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var sa=class extends En{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ir(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function wp(r,e){let t=!1;for(let o of fn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Bo={addressSorter:hn,maxParallelDials:Ji,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:yr}},ia=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Bo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Bo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Bo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Bo.dialTimeout,this.connections=t.connections??new ct,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,oe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))fn.set(n,o);this.queue=new sa({concurrency:t.maxParallelDials??Bo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,oe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Xi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Mr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new fe("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new fe("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 Mr("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:{[gp]: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:{[mp]: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 Dr(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??lu,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Ir([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return oe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:ne(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Mr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ao("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await wp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Br("The dial request has no valid addresses");let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new Ao("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!co.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var aa=class extends En{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var _p=sr(Ap(),1);var Vw=Object.prototype.toString,Hw=r=>Vw.call(r)==="[object Error]",$w=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 uu(r){return r&&Hw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:$w.has(r.message):!1}var fu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sp=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function hu(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=_p.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof fu)throw c.originalError;if(c instanceof TypeError&&!uu(c))throw c;if(Sp(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Sp(u,a,e),i(),n(u)}}})})}var ca=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new aa({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(e){!this.started||!(await this.peerStore.get(e)).tags.has(Da)||this.queue.has(e)||this.queue.add(async n=>{await hu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(n=>{this.log.error("failed to reconnect to %p",e,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Da)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};var lu=50,du={maxConnections:Yi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},la=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){if(this.maxConnections=t.maxConnections??du.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new ct,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(n=>ne(n)),this.deny=(t.deny??[]).map(n=>ne(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??du.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Zi({points:t.inboundConnectionThreshold??du.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Qi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ia(e,{addressSorter:t.addressSorter??hn,maxParallelDials:t.maxParallelDials??Ji,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:yr},connections:this.connections}),this.reconnectQueue=new ca({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),await Ru(this.dialQueue,this.reconnectQueue),this.started=!0,this.log("started")}async stop(){await Du(this.reconnectQueue,this.dialQueue);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new xt("Not started");t.signal?.throwIfAborted();let{peerId:n}=Xi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new fe("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??lu}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>ne(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var An=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var zw=1.2,Gw=2,Ww=2e3,ua=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new An(e.interval??5e3),this.failure=new An(e.interval??5e3),this.next=new An(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Gw,this.timeoutMultiplier=e.timeoutMultiplier??zw,this.minTimeout=e.minTimeout??Ww,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Ir([e.signal,n]);return oe(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var pu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=le(),this.haveNext=le()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=le(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=le(),await nr(this.readNext.promise,t?.signal,t)}};function Bp(){return new pu}var fa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var mu=class extends Error{code;constructor(e,t){super(e),this.code=t}},gu=class extends mu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function ha(r,e){let t=Bp();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new gu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new we:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new fa("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var jw=1e4,Zw="1.0.0",Xw="ping",Yw="ipfs",kp=32,da=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Yw}/${Xw}/${Zw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??jw,this.timeout=new ua({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ha(o);t=Date.now(),await Promise.all([s.write(rn(kp),{signal:n}),s.read(kp,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Jw(r){return r[Symbol.asyncIterator]!=null}function Qw(...r){let e=[];for(let t of r)Jw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=ta({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var ko=Qw;var pa=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new vo("No content routers available");let n=this,o=new br;for await(let s of ko(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new vo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new xt;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new xt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ma=globalThis.CustomEvent??Event;async function*yu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=le(),a=le(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=le(),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 ma("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ma("task-complete"))})}c=!0,o.dispatchEvent(new ma("task-complete"))}catch(p){u=p,o.dispatchEvent(new ma("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=le(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var ga=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Eo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ki("Should not try to find self");let n=this,o=ko(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Uo}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Eo("No peer routers available");let n=this,o=Hl(1024);for await(let s of yu(async function*(){let i=ko(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ya=class extends vt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,oe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,oe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ir([this.shutdownController.signal,e?.signal]);oe(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=le(),yield(await vn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,oe(1/0,this.walkController.signal);let e=Ir([this.walkController.signal,this.shutdownController.signal]);oe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=rn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await nr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var wu=32,bu=64,wa=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new qi(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new zi(`Handler already registered for protocol ${e}`);let o=bi.bind({ignoreUndefined:!0})({maxInboundStreams:wu,maxOutboundStreams:bu},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var xu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ip(r){let{name:e,metrics:t}=r,n;return t!=null?n=new xu({name:e,metrics:t}):n=new Map,n}var ba=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ip({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ot.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Wi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new xt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ot.NO_FATAL)throw new Br(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ot.FATAL_ALL)throw new Br(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Be="/multistream/1.0.0";var xa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},va=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ea=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,e={}){let t=ha(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=he(e.maxDataLength));let n=e?.lengthDecoder??st,o=e?.lengthEncoder??Ce;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new xa("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ea("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new va("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var eb=P(`
|
|
7
|
+
`);async function Tr(r,e,t){await r.write(e,t)}async function Cp(r,e,t){await r.writeV(e,t)}async function tb(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==eb[0])throw e.log.error("Invalid mss message - missing newline",t),new Ho("Missing newline");return t.sublist(0,-1)}async function or(r,e){let t=await tb(r,e);return H(t.subarray())}async function Co(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return rb(r,e[0],t);let n=Io(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Be,o);let s=P(`${Be}
|
|
8
|
+
`),i=P(`${o}
|
|
9
|
+
`);await Cp(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await or(n,t);if(t.log.trace('select: read "%s"',a),a===Be&&(t.log.trace("select: reading protocol response"),a=await or(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Tr(n,P(`${c}
|
|
10
|
+
`),t),t.log.trace("select: reading protocol response");let u=await or(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new kn("protocol selection failed")}function rb(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=le(),c=!1,u=!1,f=le(),l=!1,d=!1,h=le(),p=Io({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let x=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength);let _=`${e}
|
|
11
|
+
`;yield new we(Uint8Array.from([19]),P(`${Be}
|
|
12
|
+
`),Ce(_.length),P(_),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,v)})}x=!0}x||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Be,e),await p.writeV([P(`${Be}
|
|
13
|
+
`),P(`${e}
|
|
14
|
+
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Be,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await or(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===Be&&(b=await or(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new kn("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await nr(Promise.all(x),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:e}}function Aa(r){return r[Symbol.asyncIterator]!=null}var Sa=r=>{let e=he(r),t=ke(e);return Ce(r,t),Sa.bytes=e,t};Sa.bytes=0;function _a(r,e){e=e??{};let t=e.lengthEncoder??Sa;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Aa(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}_a.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sa;return new we(t(r.byteLength),r)};var Ba=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ka=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ia=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},To=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var nb=8,ob=1024*1024*4,Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Au=r=>{let e=st(r);return Au.bytes=he(e),e};Au.bytes=0;function Eu(r,e){let t=new we,n=Lr.LENGTH,o=-1,s=e?.lengthDecoder??Au,i=e?.maxLengthLength??nb,a=e?.maxDataLength??ob;function*c(){for(;t.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(t),o<0)throw new Ba("Invalid message length");if(o>a)throw new ka("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Lr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ia("Message length length too long");break}throw u}if(n===Lr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Lr.LENGTH}}}return Aa(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new To("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new To("Unexpected end of input")}()}Eu.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Eu(n,{...e??{},onLength:s=>{t=s}})};async function Lo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Io(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await or(n,t);if(t.log.trace('handle: read "%s"',o),o===Be){t.log.trace('handle: respond with "%s" for "%s"',Be,o),await Tr(n,P(`${Be}
|
|
15
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',Be,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Tr(n,P(`${o}
|
|
16
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new we(...e.map(i=>_a.single(P(`${i}
|
|
17
|
+
`))),P(`
|
|
18
|
+
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Tr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Tr(n,P(`na
|
|
19
|
+
`),t),t.log('handle: responded with "na" for "%s"',o)}}var ib=500,Su=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Pu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Do("the connection is being closed");if(this.status==="closed")throw new Mo("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Ur("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(ib);oe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Lp(r){return new Su(r)}var ab=3e4;function cb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return wu}function lb(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??bu}function Np(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ca=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new So(`The multiaddr connection is blocked by gater.${n}`)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Gi("connection denied");let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new Dr("inbound upgrade timeout"))};u.addEventListener("abort",f,{once:!0}),oe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new So("The multiaddr connection is blocked by gater.acceptConnection");this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the inbound connection"),l=await d.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new fe("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new Rr("inbound connection that skipped encryption must have a peer id");let h=gt(d);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new fe("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.muxers);a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:t?.limits})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=gt(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,{...t,remotePeer:o}));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new Oo("Encryption was skipped but no peer id was passed");c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,limits:t?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await Lo(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=cb(y,this.components.registrar);if(Np(y,"inbound",l)===b){let x=new $o(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`);throw p.abort(x),x}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new kr("Connection is not multiplexed");l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(ab);oe(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await Co(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=lb(b,this.components.registrar,m),x=Np(b,"outbound",l);if(x>=w){let A=new Ko(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new kr("Connection is not multiplexed")};return l=Lp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Ur("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await Lo(e,n,{log:e.log}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using",s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection failed",o),new _o(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Co(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t?.remotePeer,i),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t?.remotePeer,o),new _o(o.message)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Co(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new kr(String(o))}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Lo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new kr(String(o))}}};var Pp="1.9.4-df330695a",Rp="libp2p";var Ta=class extends vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new vt,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},oe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ai(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=lp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Rp,version:Pp},logger:this.logger,events:t,datastore:e.datastore??new Fi,connectionGater:fp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Mi(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Ca(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ba(this.components,e.transportManager)),this.configureComponent("connectionManager",new la(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new da(this.components,e.connectionMonitor)),this.configureComponent("registrar",new wa(this.components)),this.configureComponent("addressManager",new Vi(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ga(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new pa(this.components,{routers:i})),this.configureComponent("randomWalk",new ya(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Na]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Na])),u[Ra]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ra])),u[Pa]!=null&&(this.log("registering service %s for peer discovery",a),u[Pa].addEventListener?.("peer",f=>{this.#e(f)}))}up(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new br;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Qt(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=on(o);return await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function fb(r={}){r.privateKey??=await Gh("Ed25519");let e=new Ta({...await Ud(r),peerId:Xh(r.privateKey)});return r.start!==!1&&await e.start(),e}return jp(hb);})();
|
|
21
20
|
/*! Bundled license information:
|
|
22
21
|
|
|
23
22
|
pvtsutils/build/index.js:
|