libp2p 1.9.3 → 1.9.4-2bbaf4361

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.
Files changed (100) hide show
  1. package/dist/index.min.js +17 -18
  2. package/dist/src/components.d.ts.map +1 -1
  3. package/dist/src/components.js +4 -3
  4. package/dist/src/components.js.map +1 -1
  5. package/dist/src/config.d.ts +1 -1
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +2 -7
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/connection/index.d.ts +3 -3
  10. package/dist/src/connection/index.d.ts.map +1 -1
  11. package/dist/src/connection/index.js +7 -7
  12. package/dist/src/connection/index.js.map +1 -1
  13. package/dist/src/connection-manager/connection-pruner.js +1 -1
  14. package/dist/src/connection-manager/constants.browser.d.ts +0 -8
  15. package/dist/src/connection-manager/constants.browser.d.ts.map +1 -1
  16. package/dist/src/connection-manager/constants.browser.js +0 -8
  17. package/dist/src/connection-manager/constants.browser.js.map +1 -1
  18. package/dist/src/connection-manager/constants.d.ts +0 -8
  19. package/dist/src/connection-manager/constants.d.ts.map +1 -1
  20. package/dist/src/connection-manager/constants.defaults.d.ts +12 -22
  21. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  22. package/dist/src/connection-manager/constants.defaults.js +12 -22
  23. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  24. package/dist/src/connection-manager/constants.js +0 -8
  25. package/dist/src/connection-manager/constants.js.map +1 -1
  26. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  27. package/dist/src/connection-manager/dial-queue.js +29 -15
  28. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  29. package/dist/src/connection-manager/index.d.ts +47 -50
  30. package/dist/src/connection-manager/index.d.ts.map +1 -1
  31. package/dist/src/connection-manager/index.js +23 -57
  32. package/dist/src/connection-manager/index.js.map +1 -1
  33. package/dist/src/connection-manager/reconnect-queue.d.ts +35 -0
  34. package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -0
  35. package/dist/src/connection-manager/reconnect-queue.js +104 -0
  36. package/dist/src/connection-manager/reconnect-queue.js.map +1 -0
  37. package/dist/src/connection-monitor.d.ts +1 -0
  38. package/dist/src/connection-monitor.d.ts.map +1 -1
  39. package/dist/src/connection-monitor.js +15 -5
  40. package/dist/src/connection-monitor.js.map +1 -1
  41. package/dist/src/content-routing.js +6 -6
  42. package/dist/src/content-routing.js.map +1 -1
  43. package/dist/src/errors.d.ts +41 -61
  44. package/dist/src/errors.d.ts.map +1 -1
  45. package/dist/src/errors.js +84 -63
  46. package/dist/src/errors.js.map +1 -1
  47. package/dist/src/get-peer.d.ts.map +1 -1
  48. package/dist/src/get-peer.js +4 -5
  49. package/dist/src/get-peer.js.map +1 -1
  50. package/dist/src/index.d.ts +27 -9
  51. package/dist/src/index.d.ts.map +1 -1
  52. package/dist/src/index.js +10 -3
  53. package/dist/src/index.js.map +1 -1
  54. package/dist/src/libp2p.d.ts +11 -10
  55. package/dist/src/libp2p.d.ts.map +1 -1
  56. package/dist/src/libp2p.js +13 -31
  57. package/dist/src/libp2p.js.map +1 -1
  58. package/dist/src/peer-routing.js +8 -8
  59. package/dist/src/peer-routing.js.map +1 -1
  60. package/dist/src/registrar.js +7 -7
  61. package/dist/src/registrar.js.map +1 -1
  62. package/dist/src/transport-manager.d.ts.map +1 -1
  63. package/dist/src/transport-manager.js +15 -23
  64. package/dist/src/transport-manager.js.map +1 -1
  65. package/dist/src/upgrader.d.ts +8 -8
  66. package/dist/src/upgrader.d.ts.map +1 -1
  67. package/dist/src/upgrader.js +51 -51
  68. package/dist/src/upgrader.js.map +1 -1
  69. package/dist/src/version.d.ts +1 -1
  70. package/dist/src/version.d.ts.map +1 -1
  71. package/dist/src/version.js +1 -1
  72. package/dist/src/version.js.map +1 -1
  73. package/package.json +20 -20
  74. package/src/components.ts +4 -3
  75. package/src/config.ts +4 -10
  76. package/src/connection/index.ts +9 -9
  77. package/src/connection-manager/connection-pruner.ts +1 -1
  78. package/src/connection-manager/constants.browser.ts +0 -10
  79. package/src/connection-manager/constants.defaults.ts +14 -27
  80. package/src/connection-manager/constants.ts +0 -10
  81. package/src/connection-manager/dial-queue.ts +30 -15
  82. package/src/connection-manager/index.ts +80 -118
  83. package/src/connection-manager/reconnect-queue.ts +134 -0
  84. package/src/connection-monitor.ts +15 -6
  85. package/src/content-routing.ts +6 -6
  86. package/src/errors.ts +96 -61
  87. package/src/get-peer.ts +4 -5
  88. package/src/index.ts +42 -12
  89. package/src/libp2p.ts +22 -36
  90. package/src/peer-routing.ts +8 -8
  91. package/src/registrar.ts +7 -7
  92. package/src/transport-manager.ts +15 -23
  93. package/src/upgrader.ts +55 -56
  94. package/src/version.ts +1 -1
  95. package/dist/src/connection-manager/auto-dial.d.ts +0 -47
  96. package/dist/src/connection-manager/auto-dial.d.ts.map +0 -1
  97. package/dist/src/connection-manager/auto-dial.js +0 -223
  98. package/dist/src/connection-manager/auto-dial.js.map +0 -1
  99. package/dist/typedoc-urls.json +0 -14
  100. 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 mp=Object.create;var To=Object.defineProperty;var gp=Object.getOwnPropertyDescriptor;var yp=Object.getOwnPropertyNames;var wp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var _t=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)To(r,t,{get:e[t],enumerable:!0})},cu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yp(e))!bp.call(r,o)&&o!==t&&To(r,o,{get:()=>e[o],enumerable:!(n=gp(e,o))||n.enumerable});return r};var pr=(r,e,t)=>(t=r!=null?mp(wp(r)):{},cu(e||!r||!r.__esModule?To(t,"default",{value:r,enumerable:!0}):t,r)),Ep=r=>cu(To({},"__esModule",{value:!0}),r);var df=_t(on=>{"use strict";var Zg="[object ArrayBuffer]",Nt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Zg}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}},gc="string",Qg=/^[0-9a-f]+$/i,Jg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,e0=/^[a-zA-Z0-9-_]+$/,Zo=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=Nt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},tt=class{static toString(e,t=!1){let n=Nt.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}},Qo=class r{static isHex(e){return typeof e===gc&&Qg.test(e)}static isBase64(e){return typeof e===gc&&Jg.test(e)}static isBase64Url(e){return typeof e===gc&&e0.test(e)}static ToString(e,t="utf8"){let n=Nt.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 tt.toString(n,!0);case"utf16":case"utf16be":return tt.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 tt.fromString(e,!0);case"utf16":case"utf16be":return tt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Nt.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 Zo.fromString(e);case"utf16":case"utf16be":return tt.fromString(e);case"utf16le":case"usc2":return tt.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 Zo.toString(e);case"utf16":case"utf16be":return tt.toString(e);case"utf16le":case"usc2":return tt.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=Nt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Nt.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 tt.toString(e,t)}static FromUtf16String(e,t=!1){return tt.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,"")||""}};Qo.DEFAULT_UTF8_ENCODING="utf8";function t0(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 r0(...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 n0(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}on.BufferSourceConverter=Nt;on.Convert=Qo;on.assign=t0;on.combine=r0;on.isEqual=n0});var Ih=_t((io,qs)=>{(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 d=0;d<h.length;d++)if(!Number.isInteger(h[d])||h[d]<0||h[d]>255)return!1;return!0}function o(h,d){return(h&65535)*d+(((h>>>16)*d&65535)<<16)}function s(h,d){return h<<d|h>>>32-d}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,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*d[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*d[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*d[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*d[3]+h[1]*d[2]+h[2]*d[1]+h[3]*d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,d){return d%=64,d===32?[h[1],h[0]]:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d|h[0]>>>32-d]:(d-=32,[h[1]<<d|h[0]>>>32-d,h[0]<<d|h[1]>>>32-d])}function f(h,d){return d%=64,d===0?h:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d]:[h[1]<<d-32,0]}function l(h,d){return[h[0]^d[0],h[1]^d[1]]}function p(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,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%4,w=h.length-m,g=d,y=0,b=3432918353,x=461845907,A=0;A<w;A=A+4)y=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,y=o(y,b),y=s(y,15),y=o(y,x),g^=y,g=s(g,13),g=o(g,5)+3864292196;switch(y=0,m){case 3:y^=h[A+2]<<16;case 2:y^=h[A+1]<<8;case 1:y^=h[A],y=o(y,b),y=s(y,15),y=o(y,x),g^=y}return g^=h.length,g=i(g),g>>>0},t.x86.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=d,y=d,b=d,x=d,A=0,R=0,_=0,I=0,$=597399067,V=2869860233,K=951274213,Q=2716044179,D=0;D<w;D=D+16)A=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,R=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,_=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,I=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,A=o(A,$),A=s(A,15),A=o(A,V),g^=A,g=s(g,19),g+=y,g=o(g,5)+1444728091,R=o(R,V),R=s(R,16),R=o(R,K),y^=R,y=s(y,17),y+=b,y=o(y,5)+197830471,_=o(_,K),_=s(_,17),_=o(_,Q),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,I=o(I,Q),I=s(I,18),I=o(I,$),x^=I,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(A=0,R=0,_=0,I=0,m){case 15:I^=h[D+14]<<16;case 14:I^=h[D+13]<<8;case 13:I^=h[D+12],I=o(I,Q),I=s(I,18),I=o(I,$),x^=I;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,K),_=s(_,17),_=o(_,Q),b^=_;case 8:R^=h[D+7]<<24;case 7:R^=h[D+6]<<16;case 6:R^=h[D+5]<<8;case 5:R^=h[D+4],R=o(R,V),R=s(R,16),R=o(R,K),y^=R;case 4:A^=h[D+3]<<24;case 3:A^=h[D+2]<<16;case 2:A^=h[D+1]<<8;case 1:A^=h[D],A=o(A,$),A=s(A,15),A=o(A,V),g^=A}return g^=h.length,y^=h.length,b^=h.length,x^=h.length,g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,g=i(g),y=i(y),b=i(b),x=i(x),g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=[0,d],y=[0,d],b=[0,0],x=[0,0],A=[2277735313,289559509],R=[1291169091,658871167],_=0;_<w;_=_+16)b=[h[_+4]|h[_+5]<<8|h[_+6]<<16|h[_+7]<<24,h[_]|h[_+1]<<8|h[_+2]<<16|h[_+3]<<24],x=[h[_+12]|h[_+13]<<8|h[_+14]<<16|h[_+15]<<24,h[_+8]|h[_+9]<<8|h[_+10]<<16|h[_+11]<<24],b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b),g=u(g,27),g=a(g,y),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x),y=u(y,31),y=a(y,g),y=a(c(y,[0,5]),[0,944331445]);switch(b=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[_+14]],48));case 14:x=l(x,f([0,h[_+13]],40));case 13:x=l(x,f([0,h[_+12]],32));case 12:x=l(x,f([0,h[_+11]],24));case 11:x=l(x,f([0,h[_+10]],16));case 10:x=l(x,f([0,h[_+9]],8));case 9:x=l(x,[0,h[_+8]]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x);case 8:b=l(b,f([0,h[_+7]],56));case 7:b=l(b,f([0,h[_+6]],48));case 6:b=l(b,f([0,h[_+5]],40));case 5:b=l(b,f([0,h[_+4]],32));case 4:b=l(b,f([0,h[_+3]],24));case 3:b=l(b,f([0,h[_+2]],16));case 2:b=l(b,f([0,h[_+1]],8));case 1:b=l(b,[0,h[_]]),b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b)}return g=l(g,[0,h.length]),y=l(y,[0,h.length]),g=a(g,y),y=a(y,g),g=p(g),y=p(y),g=a(g,y),y=a(y,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)},typeof io<"u"?(typeof qs<"u"&&qs.exports&&(io=qs.exports=t),io.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)})(io)});var Bh=_t((Jv,Th)=>{Th.exports=Ih()});var Jh=_t((B2,tl)=>{"use strict";var Ty=Object.prototype.hasOwnProperty,He="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(He=!1));function By(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Qh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new By(t,n||r,o),i=He?He+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Zs(r,e){--r._eventsCount===0?r._events=new ho:delete r._events[e]}function Oe(){this._events=new ho,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ty.call(t,n)&&e.push(He?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Oe.prototype.listeners=function(e){var t=He?He+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Oe.prototype.listenerCount=function(e){var t=He?He+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Oe.prototype.emit=function(e,t,n,o,s,i){var a=He?He+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var p=c.length,h;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Oe.prototype.on=function(e,t,n){return Qh(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Qh(this,e,t,n,!0)};Oe.prototype.removeListener=function(e,t,n,o){var s=He?He+e:e;if(!this._events[s])return this;if(!t)return Zs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Zs(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:Zs(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&Zs(this,t)):(this._events=new ho,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=He;Oe.EventEmitter=Oe;typeof tl<"u"&&(tl.exports=Oe)});var pd=_t((WS,dd)=>{"use strict";function hd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Gy(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 hd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),hd(new o,t)}}dd.exports=Gy});var Ed=_t(yo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,p;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,p=c&255,[u,f,l,p].join(".")},i=function(c){var u,f,l,p,h,d;for(u=[],l=p=0;p<=3&&c.length!==0;l=++p){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),h=d[0],f=d[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,p,h;for(p=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)p=p*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")p=p*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")p=p*u+(10+t(c[l])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[p,l]},r=function(){function c(u,f){var l,p,h,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(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,p;for(p=i(this.first),l=i(this.last),f=0;p<=l;)u(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),yo.ip2long=i,yo.long2ip=a,yo.Netmask=r}).call(yo)});var Ld=_t((rI,Nd)=>{Nd.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 Md=_t((EI,Ud)=>{"use strict";Ud.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var qd=_t((Hd,$d)=>{"use strict";var wi=Md(),{hasOwnProperty:Vd}=Object.prototype,{propertyIsEnumerable:Ew}=Object,An=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),xw=Hd,Fd={concatArrays:!1,ignoreUndefined:!1},bi=r=>{let e=[];for(let t in r)Vd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ew.call(r,n)&&e.push(n)}return e};function Sn(r){return Array.isArray(r)?vw(r):wi(r)?_w(r):r}function vw(r){let e=r.slice(0,0);return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}function _w(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}var Kd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?An(r,o,kl(r[o],e[o],n)):An(r,o,Sn(e[o])))}),r),Aw=(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++)Vd.call(s,a)&&(i.push(String(a)),s===r?An(n,o++,s[a]):An(n,o++,Sn(s[a])));n=Kd(n,s,bi(s).filter(a=>!i.includes(a)),t)}),n};function kl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Aw(r,e,t):!wi(e)||!wi(r)?Sn(e):Kd(r,e,bi(e),t)}$d.exports=function(...r){let e=kl(Sn(Fd),this!==xw&&this||{},Fd),t={_:{}};for(let n of r)if(n!==void 0){if(!wi(n))throw new TypeError("`"+n+"` is not an Option Object");t=kl(t,{_:n},e)}return t._}});var rb={};ve(rb,{createLibp2p:()=>tb});var lu=Symbol.for("@libp2p/connection");var ia=Symbol.for("@libp2p/content-routing");var aa=Symbol.for("@libp2p/peer-discovery");var Bo=Symbol.for("@libp2p/peer-id");function Co(r){return r!=null&&!!r[Bo]}var ca=Symbol.for("@libp2p/peer-routing");var uu="keep-alive";var ub=Symbol.for("@libp2p/transport");var Ht;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var $t=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"},E=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},ko=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 No="ERR_TIMEOUT";var ie=(r,...e)=>{try{[...e]}catch{}};var At=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 la(e,t))}},la=globalThis.CustomEvent;function fu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var kn=Symbol.for("@libp2p/service-capabilities"),ua=Symbol.for("@libp2p/service-dependencies");var pc={};ve(pc,{Ed25519PrivateKey:()=>Ar,Ed25519PublicKey:()=>Hn,generateKeyPair:()=>Wg,generateKeyPairFromSeed:()=>hf,unmarshalEd25519PrivateKey:()=>Gg,unmarshalEd25519PublicKey:()=>Yg});var ma={};ve(ma,{base58btc:()=>ae,base58flickr:()=>Rp});var Vb=new Uint8Array(0);function hu(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){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 du(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}function xp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,w=0,g=0,y=d.length;g!==y&&d[g]===0;)g++,m++;for(var b=(y-g)*f+1>>>0,x=new Uint8Array(b);g!==y;){for(var A=d[g],R=0,_=b-1;(A!==0||R<w)&&_!==-1;_--,R++)A+=256*x[_]>>>0,x[_]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");w=R,g++}for(var I=b-w;I!==b&&x[I]===0;)I++;for(var $=c.repeat(m);I<b;++I)$+=r.charAt(x[I]);return $}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var w=0,g=0;d[m]===c;)w++,m++;for(var y=(d.length-m)*u+1>>>0,b=new Uint8Array(y);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var A=0,R=y-1;(x!==0||A<g)&&R!==-1;R--,A++)x+=a*b[R]>>>0,b[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=A,m++}if(d[m]!==" "){for(var _=y-g;_!==y&&b[_]===0;)_++;for(var I=new Uint8Array(w+(y-_)),$=w;_!==y;)I[$++]=b[_++];return I}}}function h(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:h}}var vp=xp,_p=vp,gu=_p;var fa=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ha=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 yu(this,e)}},da=class{decoders;constructor(e){this.decoders=e}or(e){return yu(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 yu(r,e){return new da({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var pa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new fa(e,t,n),this.decoder=new ha(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kr({name:r,prefix:e,encode:t,decode:n}){return new pa(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gu(t,r);return Kr({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function Ap(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 Sp(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 Kr({prefix:e,name:r,encode(o){return Sp(o,n,t)},decode(o){return Ap(o,n,t,r)}})}var ae=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rp=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ya={};ve(ya,{identity:()=>Rt});var Ip=Eu,wu=128,Tp=127,Bp=~Tp,Cp=Math.pow(2,31);function Eu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Cp;)e[t++]=r&255|wu,r/=128;for(;r&Bp;)e[t++]=r&255|wu,r>>>=7;return e[t]=r|0,Eu.bytes=t-n+1,e}var kp=ga,Np=128,bu=127;function ga(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ga.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&bu)<<o:(i&bu)*Math.pow(2,o),o+=7}while(i>=Np);return ga.bytes=s-n,t}var Lp=Math.pow(2,7),Dp=Math.pow(2,14),Pp=Math.pow(2,21),Op=Math.pow(2,28),Up=Math.pow(2,35),Mp=Math.pow(2,42),Fp=Math.pow(2,49),Vp=Math.pow(2,56),Kp=Math.pow(2,63),Hp=function(r){return r<Lp?1:r<Dp?2:r<Pp?3:r<Op?4:r<Up?5:r<Mp?6:r<Fp?7:r<Vp?8:r<Kp?9:10},$p={encode:Ip,decode:kp,encodingLength:Hp},qp=$p,Nn=qp;function Ln(r,e=0){return[Nn.decode(r,e),Nn.decode.bytes]}function Hr(r,e,t=0){return Nn.encode(r,e,t),e}function $r(r){return Nn.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=$r(r),o=n+$r(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new qr(r,t,e,s)}function mr(r){let e=St(r),[t,n]=Ln(e),[o,s]=Ln(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function xu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hu(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vu=0,zp="identity",_u=St;function Gp(r){return mt(vu,_u(r))}var Rt={code:vu,name:zp,encode:_u,digest:Gp};var Ea={};ve(Ea,{sha256:()=>Se,sha512:()=>Yp});function ba({name:r,code:e,encode:t}){return new wa(r,e,t)}var wa=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 Su(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Se=ba({name:"sha2-256",code:18,encode:Su("SHA-256")}),Yp=ba({name:"sha2-512",code:19,encode:Su("SHA-512")});function J(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 ke(r=0){return new Uint8Array(r)}function Re(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}var xa={};ve(xa,{base10:()=>Wp});var Wp=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var va={};ve(va,{base16:()=>jp,base16upper:()=>Xp});var jp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _a={};ve(_a,{base2:()=>Zp});var Zp=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Aa={};ve(Aa,{base256emoji:()=>rm});var Ru=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}"),Qp=Ru.reduce((r,e,t)=>(r[t]=e,r),[]),Jp=Ru.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function em(r){return r.reduce((e,t)=>(e+=Qp[t],e),"")}function tm(r){let e=[];for(let t of r){let n=Jp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rm=Kr({prefix:"\u{1F680}",name:"base256emoji",encode:em,decode:tm});var Sa={};ve(Sa,{base32:()=>Ye,base32hex:()=>im,base32hexpad:()=>cm,base32hexpadupper:()=>lm,base32hexupper:()=>am,base32pad:()=>om,base32padupper:()=>sm,base32upper:()=>nm,base32z:()=>um});var Ye=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nm=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),om=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),im=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),am=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),um=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ra={};ve(Ra,{base36:()=>fm,base36upper:()=>hm});var fm=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hm=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ta={};ve(Ta,{base64:()=>Dn,base64pad:()=>dm,base64url:()=>Ia,base64urlpad:()=>pm});var Dn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ia=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pm=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ba={};ve(Ba,{base8:()=>mm});var mm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ca={};ve(Ca,{identity:()=>gm});var gm=Kr({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>du(r)});var pE=new TextEncoder,mE=new TextDecoder;function Iu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Em(t,ka(r),e??ae.encoder);default:return xm(t,ka(r),e??Ye.encoder)}}var Tu=new WeakMap;function ka(r){let e=Tu.get(r);if(e==null){let t=new Map;return Tu.set(r,t),t}return e}var Qe=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!==Pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==vm)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&&xu(e.multihash,n.multihash)}toString(e){return Iu(this,e)}toJSON(){return{"/":Iu(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??Bu(n,o,s.bytes))}else if(t[_m]===!0){let{version:n,multihash:o,code:s}=t,i=mr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pn)throw new Error(`Version 0 CID must use dag-pb (code: ${Pn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Bu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pn,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=St(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 qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Ln(e.subarray(t));return t+=p,l},o=n(),s=Pn;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]=bm(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 ka(s).set(n,e),s}};function bm(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 Ye.prefix:{let t=e??Ye;return[Ye.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 Em(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 xm(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 Pn=112,vm=18;function Bu(r,e,t){let n=$r(r),o=n+$r(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var _m=Symbol.for("@ipld/js-cid/CID");var zt={...Ca,..._a,...Ba,...xa,...va,...Sa,...Ra,...ma,...Ta,...Aa},kE={...Ea,...ya};function ku(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cu=ku("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Na=ku("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}),Am={utf8:Cu,"utf-8":Cu,hex:zt.base16,latin1:Na,ascii:Na,binary:Na,...zt},Do=Am;function L(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Je(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function zr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Sm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...e){if(!Sm(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 Po(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(r.outputLen),zr(r.blockLen)}function Yr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Nu(r,e){Gr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Oo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var jr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var zE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Rm=async()=>{};async function Lu(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 Rm(),n+=s)}}function Du(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gt(r){return typeof r=="string"&&(r=Du(r)),Gr(r),r}function La(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Wr=class{clone(){return this._cloneInto()}},Im={}.toString;function Pu(r,e){if(e!==void 0&&Im.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Uo(r){let e=n=>r().update(Gt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xr(r=32){if(Oo&&typeof Oo.getRandomValues=="function")return Oo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Tm(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 Ou=(r,e,t)=>r&e^~r&t,Uu=(r,e,t)=>r&e^r&t^e&t,Zr=class extends Wr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=jr(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=Gt(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=jr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),Nu(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;Tm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=jr(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 Mo=BigInt(4294967295),Da=BigInt(32);function Mu(r,e=!1){return e?{h:Number(r&Mo),l:Number(r>>Da&Mo)}:{h:Number(r>>Da&Mo)|0,l:Number(r&Mo)|0}}function Bm(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}=Mu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Cm=(r,e)=>BigInt(r>>>0)<<Da|BigInt(e>>>0),km=(r,e,t)=>r>>>t,Nm=(r,e,t)=>r<<32-t|e>>>t,Lm=(r,e,t)=>r>>>t|e<<32-t,Dm=(r,e,t)=>r<<32-t|e>>>t,Pm=(r,e,t)=>r<<64-t|e>>>t-32,Om=(r,e,t)=>r>>>t-32|e<<64-t,Um=(r,e)=>e,Mm=(r,e)=>r,Fm=(r,e,t)=>r<<t|e>>>32-t,Vm=(r,e,t)=>e<<t|r>>>32-t,Km=(r,e,t)=>e<<t-32|r>>>64-t,Hm=(r,e,t)=>r<<t-32|e>>>64-t;function $m(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var qm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),zm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ym=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Wm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),jm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Xm={fromBig:Mu,split:Bm,toBig:Cm,shrSH:km,shrSL:Nm,rotrSH:Lm,rotrSL:Dm,rotrBH:Pm,rotrBL:Om,rotr32H:Um,rotr32L:Mm,rotlSH:Fm,rotlSL:Vm,rotlBH:Km,rotlBL:Hm,add:$m,add3L:qm,add3H:zm,add4L:Gm,add4H:Ym,add5H:jm,add5L:Wm},M=Xm;var[Zm,Qm]=M.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Yt=new Uint32Array(80),Wt=new Uint32Array(80),Pa=class extends Zr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:p,Gh:h,Gl:d,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=p|0,this.Gh=h|0,this.Gl=d|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let b=0;b<16;b++,t+=4)Yt[b]=e.getUint32(t),Wt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Yt[b-15]|0,A=Wt[b-15]|0,R=M.rotrSH(x,A,1)^M.rotrSH(x,A,8)^M.shrSH(x,A,7),_=M.rotrSL(x,A,1)^M.rotrSL(x,A,8)^M.shrSL(x,A,7),I=Yt[b-2]|0,$=Wt[b-2]|0,V=M.rotrSH(I,$,19)^M.rotrBH(I,$,61)^M.shrSH(I,$,6),K=M.rotrSL(I,$,19)^M.rotrBL(I,$,61)^M.shrSL(I,$,6),Q=M.add4L(_,K,Wt[b-7],Wt[b-16]),D=M.add4H(Q,R,V,Yt[b-7],Yt[b-16]);Yt[b]=D|0,Wt[b]=Q|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:p,Fh:h,Fl:d,Gh:m,Gl:w,Hh:g,Hl:y}=this;for(let b=0;b<80;b++){let x=M.rotrSH(l,p,14)^M.rotrSH(l,p,18)^M.rotrBH(l,p,41),A=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),R=l&h^~l&m,_=p&d^~p&w,I=M.add5L(y,A,_,Qm[b],Wt[b]),$=M.add5H(I,g,x,R,Zm[b],Yt[b]),V=I|0,K=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),Q=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,N=o&i^o&c^i&c;g=m|0,y=w|0,m=h|0,w=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,$|0,V|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let S=M.add3L(V,Q,N);n=M.add3H(S,$,K,D),o=S|0}({h:n,l:o}=M.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=M.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=M.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=M.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:p}=M.add(this.Eh|0,this.El|0,l|0,p|0),{h,l:d}=M.add(this.Fh|0,this.Fl|0,h|0,d|0),{h:m,l:w}=M.add(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:y}=M.add(this.Hh|0,this.Hl|0,g|0,y|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,w,g,y)}roundClean(){Yt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var On=Uo(()=>new Pa);var Vo={};ve(Vo,{aInRange:()=>qe,abool:()=>at,abytes:()=>Qr,bitGet:()=>sg,bitLen:()=>og,bitMask:()=>Mn,bitSet:()=>ig,bytesToHex:()=>Tt,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>Va,ensureBytes:()=>le,equalBytes:()=>rg,hexToBytes:()=>yr,hexToNumber:()=>Fa,inRange:()=>Un,isBytes:()=>jt,memoized:()=>br,notImplemented:()=>cg,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>Ku,numberToVarBytesBE:()=>tg,utf8ToBytes:()=>ng,validateObject:()=>gt});var Ma=BigInt(0),Fo=BigInt(1),Jm=BigInt(2);function jt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qr(r){if(!jt(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 eg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Tt(r){Qr(r);let e="";for(let t=0;t<r.length;t++)e+=eg[r[t]];return e}function Ku(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var It={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fu(r){if(r>=It._0&&r<=It._9)return r-It._0;if(r>=It._A&&r<=It._F)return r-(It._A-10);if(r>=It._a&&r<=It._f)return r-(It._a-10)}function yr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Fu(r.charCodeAt(s)),a=Fu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return Fa(Tt(r))}function Xt(r){return Qr(r),Fa(Tt(Uint8Array.from(r).reverse()))}function Zt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Zt(r,e).reverse()}function tg(r){return yr(Ku(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=yr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(jt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Ct(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Qr(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 rg(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 ng(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Oa=r=>typeof r=="bigint"&&Ma<=r;function Un(r,e,t){return Oa(r)&&Oa(e)&&Oa(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Un(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function og(r){let e;for(e=0;r>Ma;r>>=Fo,e+=1);return e}function sg(r,e){return r>>BigInt(e)&Fo}function ig(r,e,t){return r|(t?Fo:Ma)<<BigInt(e)}var Mn=r=>(Jm<<BigInt(r-1))-Fo,Ua=r=>new Uint8Array(r),Vu=r=>Uint8Array.from(r);function Va(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ua(r),o=Ua(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ua())=>{o=a(Vu([0]),l),n=a(),l.length!==0&&(o=a(Vu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,p=[];for(;l<e;){n=a();let h=n.slice();p.push(h),l+=n.length}return Ct(...p)};return(l,p)=>{i(),c(l);let h;for(;!(h=p(u()));)c();return i(),h}}var ag={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||jt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function gt(r,e,t={}){let n=(o,s,i)=>{let a=ag[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 cg=()=>{throw new Error("not implemented")};function br(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),ee=BigInt(1),Er=BigInt(2),lg=BigInt(3),Ka=BigInt(4),Hu=BigInt(5),$u=BigInt(8),ug=BigInt(9),fg=BigInt(16);function X(r,e){let t=r%e;return t>=ge?t:e+t}function hg(r,e,t){if(t<=ge||e<ge)throw new Error("Expected power/modulo > 0");if(t===ee)return ge;let n=ee;for(;e>ge;)e&ee&&(n=n*r%t),r=r*r%t,e>>=ee;return n}function te(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function Ko(r,e){if(r===ge||e<=ge)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=ge,s=ee,i=ee,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=o-i*u,p=s-a*u;n=t,t=f,o=i,s=a,i=l,a=p}if(n!==ee)throw new Error("invert: does not exist");return X(o,e)}function dg(r){let e=(r-ee)/Er,t,n,o;for(t=r-ee,n=0;t%Er===ge;t/=Er,n++);for(o=Er;o<r&&hg(o,e,r)!==r-ee;o++);if(n===1){let i=(r+ee)/Ka;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+ee)/Er;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(p);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let d=a.pow(f,ee<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function pg(r){if(r%Ka===lg){let e=(r+ee)/Ka;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%$u===Hu){let e=(r-Hu)/$u;return function(n,o){let s=n.mul(o,Er),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Er),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%fg,dg(r)}var qu=(r,e)=>(X(r,e)&ee)===ee,mg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ha(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=mg.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function gg(r,e,t){if(t<ge)throw new Error("Expected power > 0");if(t===ge)return r.ONE;if(t===ee)return e;let n=r.ONE,o=e;for(;t>ge;)t&ee&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ee;return n}function yg(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 $a(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Ho(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=$a(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=pg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Mn(o),ZERO:ge,ONE:ee,create:c=>X(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&ee)===ee,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>gg(a,c,u),div:(c,u)=>X(c*Ko(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ko(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>yg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function zu(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 qa(r){let e=zu(r);return e+Math.ceil(e/2)}function Gu(r,e,t=!1){let n=r.length,o=zu(e),s=qa(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Xt(r),a=X(i,e-ee)+ee;return t?wr(a,o):Zt(a,o)}var bg=BigInt(0),za=BigInt(1),Ga=new WeakMap,Yu=new WeakMap;function $o(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>bg;)i&za&&(a=a.add(c)),c=c.double(),i>>=za;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let p=0;p<a;p++){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,p=BigInt(2**s-1),h=2**s,d=BigInt(s);for(let m=0;m<c;m++){let w=m*u,g=Number(a&p);a>>=d,g>u&&(g-=h,a+=za);let y=w,b=w+Math.abs(g)-1,x=m%2!==0,A=g<0;g===0?l=l.add(t(x,i[y])):f=f.add(t(A,i[b]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=Yu.get(s)||1,u=Ga.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Ga.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),Yu.set(s,i),Ga.delete(s)}}}function Fn(r){return Ha(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$a(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),ze=BigInt(1),qo=BigInt(2),Eg=BigInt(8),xg={zip215:!0};function vg(r){let e=Fn(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Wu(r){let e=vg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=qo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((S,v)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(v))}}catch{return{isValid:!1,value:ct}}}),p=e.adjustScalarBytes||(S=>S),h=e.domain||((S,v,T)=>{if(at("phflag",T),v.length||T)throw new Error("Contexts/pre-hash are not supported");return S});function d(S,v){qe("coordinate "+S,v,ct,u)}function m(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=br((S,v)=>{let{ex:T,ey:B,ez:P}=S,O=S.is0();v==null&&(v=O?Eg:t.inv(P));let U=f(T*v),z=f(B*v),H=f(P*v);if(O)return{x:ct,y:ze};if(H!==ze)throw new Error("invZ was invalid");return{x:U,y:z}}),g=br(S=>{let{a:v,d:T}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:B,ey:P,ez:O,et:U}=S,z=f(B*B),H=f(P*P),G=f(O*O),oe=f(G*G),se=f(z*v),$e=f(G*f(se+H)),Ee=f(oe+f(T*f(z*H)));if($e!==Ee)throw new Error("bad point: equation left != right (1)");let me=f(B*P),nt=f(O*U);if(me!==nt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,B,P){this.ex=v,this.ey=T,this.ez=B,this.et=P,d("x",v),d("y",T),d("z",B),d("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:B}=v||{};return d("x",T),d("y",B),new y(T,B,ze,f(T*B))}static normalizeZ(v){let T=t.invertBatch(v.map(B=>B.ez));return v.map((B,P)=>B.toAffine(T[P])).map(y.fromAffine)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){g(this)}equals(v){m(v);let{ex:T,ey:B,ez:P}=this,{ex:O,ey:U,ez:z}=v,H=f(T*z),G=f(O*P),oe=f(B*z),se=f(U*P);return H===G&&oe===se}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:v}=e,{ex:T,ey:B,ez:P}=this,O=f(T*T),U=f(B*B),z=f(qo*f(P*P)),H=f(v*O),G=T+B,oe=f(f(G*G)-O-U),se=H+U,$e=se-z,Ee=H-U,me=f(oe*$e),nt=f(se*Ee),xe=f(oe*Ee),ot=f($e*se);return new y(me,nt,ot,xe)}add(v){m(v);let{a:T,d:B}=e,{ex:P,ey:O,ez:U,et:z}=this,{ex:H,ey:G,ez:oe,et:se}=v;if(T===BigInt(-1)){let tu=f((O-P)*(G+H)),ru=f((O+P)*(G-H)),sa=f(ru-tu);if(sa===ct)return this.double();let nu=f(U*qo*se),ou=f(z*qo*oe),su=ou+nu,iu=ru+tu,au=ou-nu,fp=f(su*sa),hp=f(iu*au),dp=f(su*au),pp=f(sa*iu);return new y(fp,hp,pp,dp)}let $e=f(P*H),Ee=f(O*G),me=f(z*B*se),nt=f(U*oe),xe=f((P+O)*(H+G)-$e-Ee),ot=nt-me,dr=nt+me,Cn=f(Ee-T*$e),Io=f(xe*ot),cp=f(dr*Cn),lp=f(xe*Cn),up=f(ot*dr);return new y(Io,cp,up,lp)}subtract(v){return this.add(v.negate())}wNAF(v){return A.wNAFCached(this,v,y.normalizeZ)}multiply(v){let T=v;qe("scalar",T,ze,n);let{p:B,f:P}=this.wNAF(T);return y.normalizeZ([B,P])[0]}multiplyUnsafe(v){let T=v;return qe("scalar",T,ct,n),T===ct?x:this.equals(x)||T===ze?this:this.equals(b)?this.wNAF(T).p:A.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(v){return w(this,v)}clearCofactor(){let{h:v}=e;return v===ze?this:this.multiplyUnsafe(v)}static fromHex(v,T=!1){let{d:B,a:P}=e,O=t.BYTES;v=le("pointHex",v,O),at("zip215",T);let U=v.slice(),z=v[O-1];U[O-1]=z&-129;let H=Xt(U),G=T?u:t.ORDER;qe("pointHex.y",H,ct,G);let oe=f(H*H),se=f(oe-ze),$e=f(B*oe-P),{isValid:Ee,value:me}=l(se,$e);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let nt=(me&ze)===ze,xe=(z&128)!==0;if(!T&&me===ct&&xe)throw new Error("Point.fromHex: x=0 and x_0=1");return xe!==nt&&(me=f(-me)),y.fromAffine({x:me,y:H})}static fromPrivateKey(v){return I(v).point}toRawBytes(){let{x:v,y:T}=this.toAffine(),B=wr(T,t.BYTES);return B[B.length-1]|=v&ze?128:0,B}toHex(){return Tt(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),y.ZERO=new y(ct,ze,ze,ct);let{BASE:b,ZERO:x}=y,A=$o(y,a*8);function R(S){return X(S,n)}function _(S){return R(Xt(S))}function I(S){let v=a;S=le("private key",S,v);let T=le("hashed private key",s(S),2*v),B=p(T.slice(0,v)),P=T.slice(v,2*v),O=_(B),U=b.multiply(O),z=U.toRawBytes();return{head:B,prefix:P,scalar:O,point:U,pointBytes:z}}function $(S){return I(S).pointBytes}function V(S=new Uint8Array,...v){let T=Ct(...v);return _(s(h(T,le("context",S),!!o)))}function K(S,v,T={}){S=le("message",S),o&&(S=o(S));let{prefix:B,scalar:P,pointBytes:O}=I(v),U=V(T.context,B,S),z=b.multiply(U).toRawBytes(),H=V(T.context,z,O,S),G=R(U+H*P);qe("signature.s",G,ct,n);let oe=Ct(z,wr(G,t.BYTES));return le("result",oe,a*2)}let Q=xg;function D(S,v,T,B=Q){let{context:P,zip215:O}=B,U=t.BYTES;S=le("signature",S,2*U),v=le("message",v),O!==void 0&&at("zip215",O),o&&(v=o(v));let z=Xt(S.slice(U,2*U)),H,G,oe;try{H=y.fromHex(T,O),G=y.fromHex(S.slice(0,U),O),oe=b.multiplyUnsafe(z)}catch{return!1}if(!O&&H.isSmallOrder())return!1;let se=V(P,G.toRawBytes(),H.toRawBytes(),v);return G.add(H.multiplyUnsafe(se)).subtract(oe).clearCofactor().equals(y.ZERO)}return b._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:K,verify:D,ExtendedPoint:y,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,v=y.BASE){return v._setWindowSize(S),v.multiply(BigInt(3)),v}}}}var Ya=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ju=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),px=BigInt(0),_g=BigInt(1),Xu=BigInt(2),mx=BigInt(3),Ag=BigInt(5),Sg=BigInt(8);function Rg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ya,a=r*r%s*r%s,c=te(a,Xu,s)*a%s,u=te(c,_g,s)*r%s,f=te(u,Ag,s)*u%s,l=te(f,e,s)*f%s,p=te(l,t,s)*l%s,h=te(p,n,s)*p%s,d=te(h,o,s)*h%s,m=te(d,o,s)*h%s,w=te(m,e,s)*f%s;return{pow_p_5_8:te(w,Xu,s)*r%s,b2:a}}function Ig(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Tg(r,e){let t=Ya,n=X(e*e*e,t),o=X(n*n*e,t),s=Rg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*ju,t),f=a===r,l=a===X(-r,t),p=a===X(-r*ju,t);return f&&(i=c),(l||p)&&(i=u),qu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Bg=Ho(Ya,void 0,!0),Cg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Bg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Sg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:On,randomBytes:Xr,adjustScalarBytes:Ig,uvRatio:Tg},Jr=Wu(Cg);var en=32,kt=64,zo=32;function Zu(){let r=Jr.utils.randomPrivateKey(),e=Jr.getPublicKey(r);return{privateKey:tf(r,e),publicKey:e}}function Qu(r){if(r.length!==zo)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=Jr.getPublicKey(e);return{privateKey:tf(e,t),publicKey:t}}function Ju(r,e){let t=r.subarray(0,zo);return Jr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function ef(r,e,t){return Jr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function tf(r,e){let t=new Uint8Array(kt);for(let n=0;n<zo;n++)t[n]=r[n],t[zo+n]=e[n];return t}var Ue={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 Wa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function rf(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=Ue.get();t*=8;async function c(l,p){let h=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:d};typeof p=="string"&&(p=L(p));let w;if(p.length===0){w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"]);try{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"])}}else{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,w,l);return Re([h,m.iv,new Uint8Array(g)])}async function u(l,p){let h=l.subarray(0,s),d=l.subarray(s,s+n),m=l.subarray(s+n),w={name:e,iv:d};typeof p=="string"&&(p=L(p));let g;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}let y=await a.subtle.decrypt(w,g,m);return new Uint8Array(y)}return{encrypt:c,decrypt:u}}async function tn(r,e){let n=await rf().encrypt(r,e);return Dn.encode(n)}var Lg=Math.pow(2,7),Dg=Math.pow(2,14),Pg=Math.pow(2,21),ja=Math.pow(2,28),Xa=Math.pow(2,35),Za=Math.pow(2,42),Qa=Math.pow(2,49),W=128,Ne=127;function de(r){if(r<Lg)return 1;if(r<Dg)return 2;if(r<Pg)return 3;if(r<ja)return 4;if(r<Xa)return 5;if(r<Za)return 6;if(r<Qa)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ja(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Og(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ec(r,e){let t=r[e],n=0;if(n+=t&Ne,t<W||(t=r[e+1],n+=(t&Ne)<<7,t<W)||(t=r[e+2],n+=(t&Ne)<<14,t<W)||(t=r[e+3],n+=(t&Ne)<<21,t<W)||(t=r[e+4],n+=(t&Ne)*ja,t<W)||(t=r[e+5],n+=(t&Ne)*Xa,t<W)||(t=r[e+6],n+=(t&Ne)*Za,t<W)||(t=r[e+7],n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Ug(r,e){let t=r.get(e),n=0;if(n+=t&Ne,t<W||(t=r.get(e+1),n+=(t&Ne)<<7,t<W)||(t=r.get(e+2),n+=(t&Ne)<<14,t<W)||(t=r.get(e+3),n+=(t&Ne)<<21,t<W)||(t=r.get(e+4),n+=(t&Ne)*ja,t<W)||(t=r.get(e+5),n+=(t&Ne)*Xa,t<W)||(t=r.get(e+6),n+=(t&Ne)*Za,t<W)||(t=r.get(e+7),n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Le(r,e,t=0){return e==null&&(e=ke(de(r))),e instanceof Uint8Array?Ja(r,e,t):Og(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?ec(r,e):Ug(r,e)}var tc=new Float32Array([-0]),Qt=new Uint8Array(tc.buffer);function nf(r,e,t){tc[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function of(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],tc[0]}var rc=new Float64Array([-0]),De=new Uint8Array(rc.buffer);function sf(r,e,t){rc[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function af(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],rc[0]}var Mg=BigInt(Number.MAX_SAFE_INTEGER),Fg=BigInt(Number.MIN_SAFE_INTEGER),We=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 vr;if(e<Mg&&e>Fg)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>cf&&(o=0n,++n>cf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;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):vr}},vr=new We(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var cf=4294967296n;function lf(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function uf(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 nc(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 Go(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var oc=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 Go(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return Go(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=of(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=af(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 uf(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 We(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=Go(this.buf,this.pos+=4),t=Go(this.buf,this.pos+=4);return new We(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=ec(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 sc(r){return new oc(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=sc(r);return e.decode(n,void 0,t)}function ic(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 _r=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ac(){}var lc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Vg=ic();function Kg(r){return globalThis.Buffer!=null?ke(r):Vg(r)}var Kn=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(ac,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _r(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uc((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(Yo,10,We.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=We.fromBigInt(e);return this._push(Yo,t.length(),t)}uint64Number(e){return this._push(Ja,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=We.fromBigInt(e).zzEncode();return this._push(Yo,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(Yo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(cc,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(nf,4,e)}double(e){return this._push(sf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(cc,1,0):this.uint32(t)._push($g,t,e)}string(e){let t=lf(e);return t!==0?this.uint32(t)._push(nc,t,e):this._push(cc,1,0)}fork(){return this.states=new lc(this),this.head=this.tail=new _r(ac,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new _r(ac,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=Kg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function cc(r,e,t){e[t]=r&255}function Hg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var uc=class extends _r{next;constructor(e,t){super(Hg,e,t),this.next=void 0}};function Yo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Vn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function $g(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Kn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qg,e,r),this},Kn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zg,e,r),this});function qg(r,e,t){e.set(r,t)}function zg(r,e,t){r.length<40?nc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function fc(){return new Kn}function Fe(r,e){let t=fc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(rn||(rn={}));function Wo(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 Wo("enum",rn.VARINT,t,n)}function Ve(r,e){return Wo("message",rn.LENGTH_DELIMITED,r,e)}var re;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(re||(re={}));var dc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(dc||(dc={}));(function(r){r.codec=()=>hc(dc)})(re||(re={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.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=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(yt||(yt={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.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=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(wt||(wt={}));var Hn=class{_key;constructor(e){this._key=nn(e,en)}verify(e,t){return ef(this._key,t,e)}marshal(){return this._key}get bytes(){return yt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},Ar=class{_key;_publicKey;constructor(e,t){this._key=nn(e,kt),this._publicKey=nn(t,en)}sign(e){return Ju(this._key,e)}get public(){return new Hn(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Rt.digest(this.public.bytes);return ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Gg(r){if(r.length>kt){r=nn(r,kt+en);let n=r.subarray(0,kt),o=r.subarray(kt,r.length);return new Ar(n,o)}r=nn(r,kt);let e=r.subarray(0,kt),t=r.subarray(en);return new Ar(e,t)}function Yg(r){return r=nn(r,en),new Hn(r)}async function Wg(){let{privateKey:r,publicKey:e}=Zu();return new Ar(r,e)}async function hf(r){let{privateKey:e,publicKey:t}=Qu(r);return new Ar(e,t)}function nn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function F(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ac={};ve(Ac,{MAX_RSA_KEY_SIZE:()=>eo,RsaPrivateKey:()=>ln,RsaPublicKey:()=>Jn,fromJwk:()=>x0,generateKeyPair:()=>v0,unmarshalRsaPrivateKey:()=>vc,unmarshalRsaPublicKey:()=>E0});function et(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Xr(r)}var rr={};ve(rr,{exportToPem:()=>m0,importFromPem:()=>g0,jwkToPkcs1:()=>f0,jwkToPkix:()=>d0,pkcs1ToJwk:()=>u0,pkixToJwk:()=>h0});var Xo=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Po(e);let n=Gt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Gr(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()}},$n=(r,e,t)=>new Xo(r,e).update(t).digest();$n.create=(r,e)=>new Xo(r,e);function jg(r,e,t,n){Po(r);let o=Pu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(zr(s),zr(i),zr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gt(e),u=Gt(t),f=new Uint8Array(i),l=$n.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Xg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function mc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=jg(r,e,t,n),f,l=new Uint8Array(4),p=jr(l),h=new Uint8Array(c.outputLen);for(let d=1,m=0;m<s;d++,m+=c.outputLen){let w=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),w.set(h.subarray(0,w.length)),await Lu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<w.length;g++)w[g]^=h[g]})}return Xg(c,u,a,f,h)}var q=pr(df());function Sr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Jt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Jo(...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 yc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Sr(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Sr(s,8)-n}function pf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Jt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function mf(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 Ge(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 _1=Math.log(2);function es(){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 Ot(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var zn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return wc(this.items)}},qn=[new Uint8Array([1])],gf="0123456789";var an="",ht=new ArrayBuffer(0),bc=new Uint8Array(0),Gn="EndOfContent",wf="OCTET STRING",bf="BIT STRING";function Ut(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):bc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ht)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=an,warnings:n=[],valueBeforeDecode:o=bc}={}){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)}}};Lt.NAME="baseBlock";var Pe=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pe.NAME="valueBlock";var ts=class extends Ut(Lt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):bc,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=Jt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let p=0;p<c;p++)l[p]=u[p];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Sr(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ts.NAME="identificationBlock";var rs=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Sr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Jt(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}}};rs.NAME="lengthBlock";var C={},Ie=class extends Lt{constructor({name:e=an,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ts(o),this.lenBlock=new rs(o),this.valueBlock=s?new s(o):new Pe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new zn;t||Ef(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():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 mf(t,n)}};Ie.NAME="BaseBlock";function Ef(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Ef(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Ie{constructor({value:e=an,...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}'`}};ns.NAME="BaseStringBlock";var os=class extends Ut(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};os.NAME="PrimitiveValueBlock";var xf,ss=class extends Ie{constructor(e={}){super(e,os),this.idBlock.isConstructed=!1}};xf=ss;C.Primitive=xf;ss.NAME="PRIMITIVE";function s0(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 Ms(r,e=0,t=r.length){let n=e,o=new Ie({},Pe),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ie;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=s0(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 cn(r){if(!r.byteLength){let e=new Ie({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ms(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function i0(r,e){return r?1:e}var bt=class extends Pe{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(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;i0(this.isIndefiniteForm,n)>0;){let i=Ms(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===Gn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?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 vf,er=class extends Ie{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 qp=Object.create;var Lo=Object.defineProperty;var zp=Object.getOwnPropertyDescriptor;var Gp=Object.getOwnPropertyNames;var Wp=Object.getPrototypeOf,jp=Object.prototype.hasOwnProperty;var Qt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Rt=(r,t)=>{for(var e in t)Lo(r,e,{get:t[e],enumerable:!0})},Pu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Gp(t))!jp.call(r,o)&&o!==e&&Lo(r,o,{get:()=>t[o],enumerable:!(n=zp(t,o))||n.enumerable});return r};var sr=(r,t,e)=>(e=r!=null?qp(Wp(r)):{},Pu(t||!r||!r.__esModule?Lo(e,"default",{value:r,enumerable:!0}):e,r)),Zp=r=>Pu(Lo({},"__esModule",{value:!0}),r);var Uf=Qt(Xr=>{"use strict";var w0="[object ArrayBuffer]",Ce=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===w0}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},qc="string",b0=/^[0-9a-f]+$/i,x0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v0=/^[a-zA-Z0-9-_]+$/,cs=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Ce.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Zt=class{static toString(t,e=!1){let n=Ce.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},ls=class r{static isHex(t){return typeof t===qc&&b0.test(t)}static isBase64(t){return typeof t===qc&&x0.test(t)}static isBase64Url(t){return typeof t===qc&&v0.test(t)}static ToString(t,e="utf8"){let n=Ce.toUint8Array(t);switch(e.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Zt.toString(n,!0);case"utf16":case"utf16be":return Zt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Zt.fromString(t,!0);case"utf16":case"utf16be":return Zt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Ce.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return cs.fromString(t);case"utf16":case"utf16be":return Zt.fromString(t);case"utf16le":case"usc2":return Zt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return cs.toString(t);case"utf16":case"utf16be":return Zt.toString(t);case"utf16le":case"usc2":return Zt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Ce.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ce.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Zt.toString(t,e)}static FromUtf16String(t,e=!1){return Zt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};ls.DEFAULT_UTF8_ENCODING="utf8";function E0(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function A0(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function S0(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}Xr.BufferSourceConverter=Ce;Xr.Convert=ls;Xr.assign=E0;Xr.combine=A0;Xr.isEqual=S0});var yd=Qt(co=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+e(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),co.ip2long=i,co.long2ip=a,co.Netmask=r}).call(co)});var xd=Qt((aS,Cl)=>{"use strict";var Cy=Object.prototype.hasOwnProperty,Vt="~";function lo(){}Object.create&&(lo.prototype=Object.create(null),new lo().__proto__||(Vt=!1));function Ty(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function bd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Ty(e,n||r,o),i=Vt?Vt+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function hi(r,t){--r._eventsCount===0?r._events=new lo:delete r._events[t]}function Nt(){this._events=new lo,this._eventsCount=0}Nt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Cy.call(e,n)&&t.push(Vt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Nt.prototype.listeners=function(t){var e=Vt?Vt+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Nt.prototype.listenerCount=function(t){var e=Vt?Vt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Nt.prototype.emit=function(t,e,n,o,s,i){var a=Vt?Vt+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,n);break;case 4:c[l].fn.call(c[l].context,e,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Nt.prototype.on=function(t,e,n){return bd(this,t,e,n,!1)};Nt.prototype.once=function(t,e,n){return bd(this,t,e,n,!0)};Nt.prototype.removeListener=function(t,e,n,o){var s=Vt?Vt+t:t;if(!this._events[s])return this;if(!e)return hi(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&hi(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:hi(this,s)}return this};Nt.prototype.removeAllListeners=function(t){var e;return t?(e=Vt?Vt+t:t,this._events[e]&&hi(this,e)):(this._events=new lo,this._eventsCount=0),this};Nt.prototype.off=Nt.prototype.removeListener;Nt.prototype.addListener=Nt.prototype.on;Nt.prefixed=Vt;Nt.EventEmitter=Nt;typeof Cl<"u"&&(Cl.exports=Nt)});var _d=Qt((TS,Sd)=>{Sd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Td=Qt((WS,Cd)=>{"use strict";Cd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var Md=Qt((Rd,Dd)=>{"use strict";var gi=Td(),{hasOwnProperty:Nd}=Object.prototype,{propertyIsEnumerable:Dy}=Object,hn=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),My=Rd,Ld={concatArrays:!1,ignoreUndefined:!1},yi=r=>{let t=[];for(let e in r)Nd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)Dy.call(r,n)&&t.push(n)}return t};function dn(r){return Array.isArray(r)?Uy(r):gi(r)?Oy(r):r}function Uy(r){let t=r.slice(0,0);return yi(r).forEach(e=>{hn(t,e,dn(r[e]))}),t}function Oy(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return yi(r).forEach(e=>{hn(t,e,dn(r[e]))}),t}var Pd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?hn(r,o,Ul(r[o],t[o],n)):hn(r,o,dn(t[o])))}),r),Fy=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Nd.call(s,a)&&(i.push(String(a)),s===r?hn(n,o++,s[a]):hn(n,o++,dn(s[a])));n=Pd(n,s,yi(s).filter(a=>!i.includes(a)),e)}),n};function Ul(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?Fy(r,t,e):!gi(t)||!gi(r)?dn(t):Pd(r,t,yi(t),e)}Dd.exports=function(...r){let t=Ul(dn(Ld),this!==My&&this||{},Ld),e={_:{}};for(let n of r)if(n!==void 0){if(!gi(n))throw new TypeError("`"+n+"` is not an Option Object");e=Ul(e,{_:n},t)}return e._}});var Vd=Qt((po,Si)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,x=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,x),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,x),y^=b}return y^=h.length,y=i(y),y>>>0},e.x86.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,x=p,A=0,_=0,v=0,B=0,T=597399067,et=2869860233,V=951274213,F=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,T),A=s(A,15),A=o(A,et),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,_=o(_,et),_=s(_,16),_=o(_,V),b^=_,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,V),v=s(v,17),v=o(v,F),w^=v,w=s(w,15),w+=x,w=o(w,5)+2530024501,B=o(B,F),B=s(B,18),B=o(B,T),x^=B,x=s(x,13),x+=y,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,F),B=s(B,18),B=o(B,T),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,V),v=s(v,17),v=o(v,F),w^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,et),_=s(_,16),_=o(_,V),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,T),A=s(A,15),A=o(A,et),y^=A}return y^=h.length,b^=h.length,w^=h.length,x^=h.length,y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,y=i(y),b=i(b),w=i(w),x=i(x),y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},e.x64.hash128=function(h,p){if(e.inputValidation&&!n(h))return t;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],x=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[v+14]],48));case 14:x=l(x,f([0,h[v+13]],40));case 13:x=l(x,f([0,h[v+12]],32));case 12:x=l(x,f([0,h[v+11]],24));case 11:x=l(x,f([0,h[v+10]],16));case 10:x=l(x,f([0,h[v+9]],8));case 9:x=l(x,[0,h[v+8]]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof po<"u"?(typeof Si<"u"&&Si.exports&&(po=Si.exports=e),po.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(po)});var $d=Qt((E8,Hd)=>{Hd.exports=Vd()});var vp=Qt((iB,xp)=>{function Jt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}xp.exports=Jt;Jt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Jt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Jt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Jt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Jt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Jt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Jt.prototype.start=Jt.prototype.try;Jt.prototype.errors=function(){return this._errors};Jt.prototype.attempts=function(){return this._attempts};Jt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Ep=Qt(Cr=>{var Vw=vp();Cr.operation=function(r){var t=Cr.timeouts(r);return new Vw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Cr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Cr.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Cr.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Cr.operation(t),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=t}}});var Sp=Qt((cB,Ap)=>{Ap.exports=Ep()});var pb={};Rt(pb,{createLibp2p:()=>db});var Ru=Symbol.for("@libp2p/connection");var La=Symbol.for("@libp2p/content-routing");var Na=Symbol.for("@libp2p/peer-discovery");var No=Symbol.for("@libp2p/peer-id");function Po(r){return!!r?.[No]}var Pa=Symbol.for("@libp2p/peer-routing");var Ra="keep-alive";var Eb=Symbol.for("@libp2p/transport");var Oe;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Oe||(Oe={}));var be=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var D=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Nr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},_n=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Ro=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Do=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Mo=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Uo=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Pr=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Oo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Fo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Bn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Vo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Rr=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},xe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Dr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Mr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Ho=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},$o=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Fe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var tt=(r,...t)=>{try{[...t]}catch{}};var ve=class extends EventTarget{#t=new Map;constructor(){super(),tt(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Ko(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Du(...r){let t=[];for(let e of r)Ko(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Mu(...r){let t=[];for(let e of r)Ko(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var In=Symbol.for("@libp2p/service-capabilities"),Da=Symbol.for("@libp2p/service-dependencies");var Va={};Rt(Va,{base58btc:()=>W,base58flickr:()=>em});var Jb=new Uint8Array(0);function Uu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ou(r){return new TextEncoder().encode(r)}function Fu(r){return new TextDecoder().decode(r)}function Xp(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,x=new Uint8Array(w);y!==b;){for(var A=p[y],_=0,v=w-1;(A!==0||_<g)&&v!==-1;v--,_++)A+=256*x[v]>>>0,x[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=_,y++}for(var B=w-g;B!==w&&x[B]===0;)B++;for(var T=c.repeat(m);B<w;++B)T+=r.charAt(x[B]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var x=e[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<y)&&_!==-1;_--,A++)x+=a*w[_]>>>0,w[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),T=g;v!==b;)B[T++]=w[v++];return B}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Yp=Xp,Jp=Yp,Hu=Jp;var Ma=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ua=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $u(this,t)}},Oa=class{decoders;constructor(t){this.decoders=t}or(t){return $u(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function $u(r,t){return new Oa({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Fa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ma(t,e,n),this.decoder=new Ua(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ur({name:r,prefix:t,encode:e,decode:n}){return new Fa(r,t,e,n)}function Ve({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Hu(e,r);return Ur({prefix:t,name:r,encode:n,decode:s=>Ee(o(s))})}function Qp(r,t,e,n){let o={};for(let f=0;f<t.length;++f)o[t[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|l,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function tm(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ur({prefix:t,name:r,encode(o){return tm(o,n,e)},decode(o){return Qp(o,n,e,r)}})}var W=Ve({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),em=Ve({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ha={};Rt(Ha,{base32:()=>zt,base32hex:()=>sm,base32hexpad:()=>am,base32hexpadupper:()=>cm,base32hexupper:()=>im,base32pad:()=>nm,base32padupper:()=>om,base32upper:()=>rm,base32z:()=>lm});var zt=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rm=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nm=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),om=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),sm=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),im=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),am=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),cm=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),lm=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var um=zu,Ku=128,fm=127,hm=~fm,dm=Math.pow(2,31);function zu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=dm;)t[e++]=r&255|Ku,r/=128;for(;r&hm;)t[e++]=r&255|Ku,r>>>=7;return t[e]=r|0,zu.bytes=e-n+1,t}var pm=$a,mm=128,qu=127;function $a(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $a.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qu)<<o:(i&qu)*Math.pow(2,o),o+=7}while(i>=mm);return $a.bytes=s-n,e}var gm=Math.pow(2,7),ym=Math.pow(2,14),wm=Math.pow(2,21),bm=Math.pow(2,28),xm=Math.pow(2,35),vm=Math.pow(2,42),Em=Math.pow(2,49),Am=Math.pow(2,56),Sm=Math.pow(2,63),_m=function(r){return r<gm?1:r<ym?2:r<wm?3:r<bm?4:r<xm?5:r<vm?6:r<Em?7:r<Am?8:r<Sm?9:10},Bm={encode:um,decode:pm,encodingLength:_m},Im=Bm,kn=Im;function Cn(r,t=0){return[kn.decode(r,t),kn.decode.bytes]}function Or(r,t,e=0){return kn.encode(r,t,e),t}function Fr(r){return kn.encodingLength(r)}function te(r,t){let e=t.byteLength,n=Fr(r),o=n+Fr(e),s=new Uint8Array(o+e);return Or(r,s,0),Or(e,s,n),s.set(t,o),new Vr(r,e,t,s)}function ee(r){let t=Ee(r),[e,n]=Cn(t),[o,s]=Cn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Vr(e,o,i,t)}function Gu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Uu(r.bytes,e.bytes)}}var Vr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Wu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Cm(e,Ka(r),t??W.encoder);default:return Tm(e,Ka(r),t??zt.encoder)}}var ju=new WeakMap;function Ka(r){let t=ju.get(r);if(t==null){let e=new Map;return ju.set(r,e),e}return t}var pt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Lm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=te(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Gu(t.multihash,n.multihash)}toString(t){return Wu(this,t)}toJSON(){return{"/":Wu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Zu(n,o,s.bytes))}else if(e[Nm]===!0){let{version:n,multihash:o,code:s}=e,i=ee(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Tn)throw new Error(`Version 0 CID must use dag-pb (code: ${Tn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Zu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Tn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Vr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=Cn(t.subarray(e));return e+=d,l},o=n(),s=Tn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=km(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ka(s).set(n,t),s}};function km(r,t){switch(r[0]){case"Q":{let e=t??W;return[W.prefix,e.decode(`${W.prefix}${r}`)]}case W.prefix:{let e=t??W;return[W.prefix,e.decode(r)]}case zt.prefix:{let e=t??zt;return[zt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Cm(r,t,e){let{prefix:n}=e;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Tm(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Tn=112,Lm=18;function Zu(r,t,e){let n=Fr(r),o=n+Fr(t),s=new Uint8Array(o+e.byteLength);return Or(r,s,0),Or(t,s,n),s.set(e,o),s}var Nm=Symbol.for("@ipld/js-cid/CID");var qa={};Rt(qa,{identity:()=>Se});var Xu=0,Pm="identity",Yu=Ee;function Rm(r){return te(Xu,Yu(r))}var Se={code:Xu,name:Pm,encode:Yu,digest:Rm};function it(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ju(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Dm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Hr(r,...t){if(!Dm(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function Qu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ju(r.outputLen),Ju(r.blockLen)}function $r(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function tf(r,t){Hr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var zo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),re=(r,t)=>r<<32-t|r>>>t;var bx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Ln(r){return typeof r=="string"&&(r=ef(r)),Hr(r),r}function za(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Hr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Kr=class{clone(){return this._cloneInto()}},xx={}.toString;function Go(r){let t=n=>r().update(Ln(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function qr(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 Mm(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}var rf=(r,t,e)=>r&t^~r&e,nf=(r,t,e)=>r&t^r&e^t&e,zr=class extends Kr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=zo(this.buffer)}update(t){$r(this);let{view:e,buffer:n,blockLen:o}=this;t=Ln(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){$r(this),tf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;Mm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=zo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Wo=BigInt(4294967295),Ga=BigInt(32);function of(r,t=!1){return t?{h:Number(r&Wo),l:Number(r>>Ga&Wo)}:{h:Number(r>>Ga&Wo)|0,l:Number(r&Wo)|0}}function Um(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=of(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Om=(r,t)=>BigInt(r>>>0)<<Ga|BigInt(t>>>0),Fm=(r,t,e)=>r>>>e,Vm=(r,t,e)=>r<<32-e|t>>>e,Hm=(r,t,e)=>r>>>e|t<<32-e,$m=(r,t,e)=>r<<32-e|t>>>e,Km=(r,t,e)=>r<<64-e|t>>>e-32,qm=(r,t,e)=>r>>>e-32|t<<64-e,zm=(r,t)=>t,Gm=(r,t)=>r,Wm=(r,t,e)=>r<<e|t>>>32-e,jm=(r,t,e)=>t<<e|r>>>32-e,Zm=(r,t,e)=>t<<e-32|r>>>64-e,Xm=(r,t,e)=>r<<e-32|t>>>64-e;function Ym(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Jm=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Qm=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,tg=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),eg=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,rg=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),ng=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var og={fromBig:of,split:Um,toBig:Om,shrSH:Fm,shrSL:Vm,rotrSH:Hm,rotrSL:$m,rotrBH:Km,rotrBL:qm,rotr32H:zm,rotr32L:Gm,rotlSH:Wm,rotlSL:jm,rotlBH:Zm,rotlBL:Xm,add:Ym,add3L:Jm,add3H:Qm,add4L:tg,add4H:eg,add5H:ng,add5L:rg},O=og;var[sg,ig]=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))),He=new Uint32Array(80),$e=new Uint32Array(80),Wa=class extends zr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(t,e,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(t,e){for(let w=0;w<16;w++,e+=4)He[w]=t.getUint32(e),$e[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let x=He[w-15]|0,A=$e[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=He[w-2]|0,T=$e[w-2]|0,et=O.rotrSH(B,T,19)^O.rotrBH(B,T,61)^O.shrSH(B,T,6),V=O.rotrSL(B,T,19)^O.rotrBL(B,T,61)^O.shrSL(B,T,6),F=O.add4L(v,V,$e[w-7],$e[w-16]),R=O.add4H(F,_,et,He[w-7],He[w-16]);He[w]=R|0,$e[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,ig[w],$e[w]),T=O.add5H(B,y,x,_,sg[w],He[w]),et=B|0,V=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),F=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),R=n&s^n&a^s&a,k=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=O.add(u|0,f|0,T|0,et|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=O.add3L(et,F,k);n=O.add3H(L,T,V,R),o=L|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=O.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=O.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=O.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=O.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){He.fill(0),$e.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var sf=Go(()=>new Wa);var Zo={};Rt(Zo,{aInRange:()=>$t,abool:()=>ne,abytes:()=>Gr,bitGet:()=>hg,bitLen:()=>Ja,bitMask:()=>Pn,bitSet:()=>dg,bytesToHex:()=>Be,bytesToNumberBE:()=>Ie,bytesToNumberLE:()=>qe,concatBytes:()=>ke,createHmacDrbg:()=>Qa,ensureBytes:()=>at,equalBytes:()=>ug,hexToBytes:()=>cr,hexToNumber:()=>Ya,inRange:()=>Nn,isBytes:()=>Ke,memoized:()=>ur,notImplemented:()=>mg,numberToBytesBE:()=>ze,numberToBytesLE:()=>lr,numberToHexUnpadded:()=>ar,numberToVarBytesBE:()=>lg,utf8ToBytes:()=>fg,validateObject:()=>ue});var Xa=BigInt(0),jo=BigInt(1),ag=BigInt(2);function Ke(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r){if(!Ke(r))throw new Error("Uint8Array expected")}function ne(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var cg=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Be(r){Gr(r);let t="";for(let e=0;e<r.length;e++)t+=cg[r[e]];return t}function ar(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ya(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _e={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function af(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e._A&&r<=_e._F)return r-(_e._A-10);if(r>=_e._a&&r<=_e._f)return r-(_e._a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=af(r.charCodeAt(s)),a=af(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ie(r){return Ya(Be(r))}function qe(r){return Gr(r),Ya(Be(Uint8Array.from(r).reverse()))}function ze(r,t){return cr(r.toString(16).padStart(t*2,"0"))}function lr(r,t){return ze(r,t).reverse()}function lg(r){return cr(ar(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=cr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Ke(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function ke(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function ug(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function fg(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var ja=r=>typeof r=="bigint"&&Xa<=r;function Nn(r,t,e){return ja(r)&&ja(t)&&ja(e)&&t<=r&&r<e}function $t(r,t,e,n){if(!Nn(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function Ja(r){let t;for(t=0;r>Xa;r>>=jo,t+=1);return t}function hg(r,t){return r>>BigInt(t)&jo}function dg(r,t,e){return r|(e?jo:Xa)<<BigInt(t)}var Pn=r=>(ag<<BigInt(r-1))-jo,Za=r=>new Uint8Array(r),cf=r=>Uint8Array.from(r);function Qa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Za(r),o=Za(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>e(o,n,...l),c=(l=Za())=>{o=a(cf([0]),l),n=a(),l.length!==0&&(o=a(cf([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<t;){n=a();let h=n.slice();d.push(h),l+=n.length}return ke(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var pg={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"||Ke(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ue(r,t,e={}){let n=(o,s,i)=>{let a=pg[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var mg=()=>{throw new Error("not implemented")};function ur(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var mt=BigInt(0),rt=BigInt(1),fr=BigInt(2),gg=BigInt(3),tc=BigInt(4),lf=BigInt(5),uf=BigInt(8),yg=BigInt(9),wg=BigInt(16);function Y(r,t){let e=r%t;return e>=mt?e:t+e}function bg(r,t,e){if(e<=mt||t<mt)throw new Error("Expected power/modulo > 0");if(e===rt)return mt;let n=rt;for(;t>mt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >mt;)n*=n,n%=e;return n}function Xo(r,t){if(r===mt||t<=mt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=Y(r,t),n=t,o=mt,s=rt,i=rt,a=mt;for(;e!==mt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==rt)throw new Error("invert: does not exist");return Y(o,t)}function xg(r){let t=(r-rt)/fr,e,n,o;for(e=r-rt,n=0;e%fr===mt;e/=fr,n++);for(o=fr;o<r&&bg(o,t,r)!==r-rt;o++);if(n===1){let i=(r+rt)/tc;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(e+rt)/fr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),e),l=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,rt<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function vg(r){if(r%tc===gg){let t=(r+rt)/tc;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%uf===lf){let t=(r-lf)/uf;return function(n,o){let s=n.mul(o,fr),i=n.pow(s,t),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%wg,xg(r)}var ff=(r,t)=>(Y(r,t)&rt)===rt,Eg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ec(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Eg.reduce((n,o)=>(n[o]="function",n),t);return ue(r,e)}function Ag(r,t,e){if(e<mt)throw new Error("Expected power > 0");if(e===mt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>mt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function Sg(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function rc(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ge(r,t,e=!1,n={}){if(r<=mt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=rc(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=vg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Pn(o),ZERO:mt,ONE:rt,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return mt<=c&&c<r},is0:c=>c===mt,isOdd:c=>(c&rt)===rt,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>Ag(a,c,u),div:(c,u)=>Y(c*Xo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Xo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Sg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>e?lr(c,s):ze(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?qe(c):Ie(c)}});return Object.freeze(a)}function hf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function nc(r){let t=hf(r);return t+Math.ceil(t/2)}function df(r,t,e=!1){let n=r.length,o=hf(t),s=nc(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Ie(r):qe(r),a=Y(i,t-rt)+rt;return e?lr(a,o):ze(a,o)}var Bg=BigInt(0),oc=BigInt(1),sc=new WeakMap,pf=new WeakMap;function Yo(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>Bg;)i&oc&&(a=a.add(c)),c=c.double(),i>>=oc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=oc);let b=g,w=g+Math.abs(y)-1,x=m%2!==0,A=y<0;y===0?l=l.add(e(x,i[b])):f=f.add(e(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=pf.get(s)||1,u=sc.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&sc.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),pf.set(s,i),sc.delete(s)}}}function Jo(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!t.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),e.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Ja(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(e[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function Rn(r){return ec(r.Fp),ue(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var oe=BigInt(0),Kt=BigInt(1),Qo=BigInt(2),Ig=BigInt(8),kg={zip215:!0};function Cg(r){let t=Rn(r);return ue(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function mf(r){let t=Cg(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=Qo<<BigInt(a*8)-Kt,f=e.create,l=Ge(t.n,t.nBitLength),d=t.uvRatio||((S,E)=>{try{return{isValid:!0,value:e.sqrt(S*e.inv(E))}}catch{return{isValid:!1,value:oe}}}),h=t.adjustScalarBytes||(S=>S),p=t.domain||((S,E,I)=>{if(ne("phflag",I),E.length||I)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){$t("coordinate "+S,E,oe,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=ur((S,E)=>{let{ex:I,ey:N,ez:M}=S,U=S.is0();E==null&&(E=U?Ig:e.inv(M));let $=f(I*E),z=f(N*E),K=f(M*E);if(U)return{x:oe,y:Kt};if(K!==Kt)throw new Error("invZ was invalid");return{x:$,y:z}}),b=ur(S=>{let{a:E,d:I}=t;if(S.is0())throw new Error("bad point: ZERO");let{ex:N,ey:M,ez:U,et:$}=S,z=f(N*N),K=f(M*M),X=f(U*U),Q=f(X*X),bt=f(z*E),xt=f(X*f(bt+K)),Et=f(Q+f(I*f(z*K)));if(xt!==Et)throw new Error("bad point: equation left != right (1)");let Pt=f(N*M),dt=f(U*$);if(Pt!==dt)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,I,N,M){this.ex=E,this.ey=I,this.ez=N,this.et=M,m("x",E),m("y",I),m("z",N),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");let{x:I,y:N}=E||{};return m("x",I),m("y",N),new w(I,N,Kt,f(I*N))}static normalizeZ(E){let I=e.invertBatch(E.map(N=>N.ez));return E.map((N,M)=>N.toAffine(I[M])).map(w.fromAffine)}static msm(E,I){return Jo(w,l,E,I)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:I,ey:N,ez:M}=this,{ex:U,ey:$,ez:z}=E,K=f(I*z),X=f(U*M),Q=f(N*z),bt=f($*M);return K===X&&Q===bt}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=t,{ex:I,ey:N,ez:M}=this,U=f(I*I),$=f(N*N),z=f(Qo*f(M*M)),K=f(E*U),X=I+N,Q=f(f(X*X)-U-$),bt=K+$,xt=bt-z,Et=K-$,Pt=f(Q*xt),dt=f(bt*Et),Ht=f(Q*Et),we=f(xt*bt);return new w(Pt,dt,we,Ht)}add(E){g(E);let{a:I,d:N}=t,{ex:M,ey:U,ez:$,et:z}=this,{ex:K,ey:X,ez:Q,et:bt}=E;if(I===BigInt(-1)){let Bu=f((U-M)*(X+K)),Iu=f((U+M)*(X-K)),Ta=f(Iu-Bu);if(Ta===oe)return this.double();let ku=f($*Qo*bt),Cu=f(z*Qo*Q),Tu=Cu+ku,Lu=Iu+Bu,Nu=Cu-ku,Vp=f(Tu*Ta),Hp=f(Lu*Nu),$p=f(Tu*Nu),Kp=f(Ta*Lu);return new w(Vp,Hp,Kp,$p)}let xt=f(M*K),Et=f(U*X),Pt=f(z*N*bt),dt=f($*Q),Ht=f((M+U)*(K+X)-xt-Et),we=dt-Pt,An=dt+Pt,Sn=f(Et-I*xt),Mp=f(Ht*we),Up=f(An*Sn),Op=f(Ht*Sn),Fp=f(we*An);return new w(Mp,Up,Fp,Op)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){let I=E;$t("scalar",I,Kt,n);let{p:N,f:M}=this.wNAF(I);return w.normalizeZ([N,M])[0]}multiplyUnsafe(E){let I=E;return $t("scalar",I,oe,n),I===oe?A:this.equals(A)||I===Kt?this:this.equals(x)?this.wNAF(I).p:_.unsafeLadder(this,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return y(this,E)}clearCofactor(){let{h:E}=t;return E===Kt?this:this.multiplyUnsafe(E)}static fromHex(E,I=!1){let{d:N,a:M}=t,U=e.BYTES;E=at("pointHex",E,U),ne("zip215",I);let $=E.slice(),z=E[U-1];$[U-1]=z&-129;let K=qe($),X=I?u:e.ORDER;$t("pointHex.y",K,oe,X);let Q=f(K*K),bt=f(Q-Kt),xt=f(N*Q-M),{isValid:Et,value:Pt}=d(bt,xt);if(!Et)throw new Error("Point.fromHex: invalid y coordinate");let dt=(Pt&Kt)===Kt,Ht=(z&128)!==0;if(!I&&Pt===oe&&Ht)throw new Error("Point.fromHex: x=0 and x_0=1");return Ht!==dt&&(Pt=f(-Pt)),w.fromAffine({x:Pt,y:K})}static fromPrivateKey(E){return T(E).point}toRawBytes(){let{x:E,y:I}=this.toAffine(),N=lr(I,e.BYTES);return N[N.length-1]|=E&Kt?128:0,N}toHex(){return Be(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Kt,f(t.Gx*t.Gy)),w.ZERO=new w(oe,Kt,Kt,oe);let{BASE:x,ZERO:A}=w,_=Yo(w,a*8);function v(S){return Y(S,n)}function B(S){return v(qe(S))}function T(S){let E=a;S=at("private key",S,E);let I=at("hashed private key",s(S),2*E),N=h(I.slice(0,E)),M=I.slice(E,2*E),U=B(N),$=x.multiply(U),z=$.toRawBytes();return{head:N,prefix:M,scalar:U,point:$,pointBytes:z}}function et(S){return T(S).pointBytes}function V(S=new Uint8Array,...E){let I=ke(...E);return B(s(p(I,at("context",S),!!o)))}function F(S,E,I={}){S=at("message",S),o&&(S=o(S));let{prefix:N,scalar:M,pointBytes:U}=T(E),$=V(I.context,N,S),z=x.multiply($).toRawBytes(),K=V(I.context,z,U,S),X=v($+K*M);$t("signature.s",X,oe,n);let Q=ke(z,lr(X,e.BYTES));return at("result",Q,a*2)}let R=kg;function k(S,E,I,N=R){let{context:M,zip215:U}=N,$=e.BYTES;S=at("signature",S,2*$),E=at("message",E),U!==void 0&&ne("zip215",U),o&&(E=o(E));let z=qe(S.slice($,2*$)),K,X,Q;try{K=w.fromHex(I,U),X=w.fromHex(S.slice(0,$),U),Q=x.multiplyUnsafe(z)}catch{return!1}if(!U&&K.isSmallOrder())return!1;let bt=V(M,X.toRawBytes(),K.toRawBytes(),E);return X.add(K.multiplyUnsafe(bt)).subtract(Q).clearCofactor().equals(w.ZERO)}return x._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:F,verify:k,ExtendedPoint:w,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(S=8,E=w.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var ic=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Kx=BigInt(0),Tg=BigInt(1),yf=BigInt(2),qx=BigInt(3),Lg=BigInt(5),Ng=BigInt(8);function Pg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ic,a=r*r%s*r%s,c=nt(a,yf,s)*a%s,u=nt(c,Tg,s)*r%s,f=nt(u,Lg,s)*u%s,l=nt(f,t,s)*f%s,d=nt(l,e,s)*l%s,h=nt(d,n,s)*d%s,p=nt(h,o,s)*h%s,m=nt(p,o,s)*h%s,g=nt(m,t,s)*f%s;return{pow_p_5_8:nt(g,yf,s)*r%s,b2:a}}function Rg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Dg(r,t){let e=ic,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Pg(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*gf,e),f=a===r,l=a===Y(-r,e),d=a===Y(-r*gf,e);return f&&(i=c),(l||d)&&(i=u),ff(i,e)&&(i=Y(-i,e)),{isValid:f||l,value:i}}var Mg=Ge(ic,void 0,!0),Ug={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Mg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ng,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sf,randomBytes:qr,adjustScalarBytes:Rg,uvRatio:Dg},Dn=mf(Ug);var ts=32,es=64,ac=32;function wf(){let r=Dn.utils.randomPrivateKey(),t=Dn.getPublicKey(r);return{privateKey:Og(r,t),publicKey:t}}function bf(r,t){let e=r.subarray(0,ac);return Dn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function xf(r,t,e){return Dn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Og(r,t){let e=new Uint8Array(es);for(let n=0;n<ac;n++)e[n]=r[n],e[ac+n]=t[n];return e}var Mn=class{type="Ed25519";raw;constructor(t){this.raw=ns(t,ts)}toMultihash(){return Se.digest(fe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return xf(this.raw,e,t)}},rs=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=ns(t,es),this.publicKey=new Mn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return bf(this.raw,t)}};function cc(r){return r=ns(r,ts),new Mn(r)}async function Ef(){let{privateKey:r,publicKey:t}=wf();return new rs(r,t)}function ns(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function ct(r=0){return new Uint8Array(r)}function It(r=0){return new Uint8Array(r)}var Fg=Math.pow(2,7),Vg=Math.pow(2,14),Hg=Math.pow(2,21),lc=Math.pow(2,28),uc=Math.pow(2,35),fc=Math.pow(2,42),hc=Math.pow(2,49),j=128,kt=127;function ht(r){if(r<Fg)return 1;if(r<Vg)return 2;if(r<Hg)return 3;if(r<lc)return 4;if(r<uc)return 5;if(r<fc)return 6;if(r<hc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function dc(r,t,e=0){switch(ht(r)){case 8:t[e++]=r&255|j,r/=128;case 7:t[e++]=r&255|j,r/=128;case 6:t[e++]=r&255|j,r/=128;case 5:t[e++]=r&255|j,r/=128;case 4:t[e++]=r&255|j,r>>>=7;case 3:t[e++]=r&255|j,r>>>=7;case 2:t[e++]=r&255|j,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function $g(r,t,e=0){switch(ht(r)){case 8:t.set(e++,r&255|j),r/=128;case 7:t.set(e++,r&255|j),r/=128;case 6:t.set(e++,r&255|j),r/=128;case 5:t.set(e++,r&255|j),r/=128;case 4:t.set(e++,r&255|j),r>>>=7;case 3:t.set(e++,r&255|j),r>>>=7;case 2:t.set(e++,r&255|j),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function pc(r,t){let e=r[t],n=0;if(n+=e&kt,e<j||(e=r[t+1],n+=(e&kt)<<7,e<j)||(e=r[t+2],n+=(e&kt)<<14,e<j)||(e=r[t+3],n+=(e&kt)<<21,e<j)||(e=r[t+4],n+=(e&kt)*lc,e<j)||(e=r[t+5],n+=(e&kt)*uc,e<j)||(e=r[t+6],n+=(e&kt)*fc,e<j)||(e=r[t+7],n+=(e&kt)*hc,e<j))return n;throw new RangeError("Could not decode varint")}function Kg(r,t){let e=r.get(t),n=0;if(n+=e&kt,e<j||(e=r.get(t+1),n+=(e&kt)<<7,e<j)||(e=r.get(t+2),n+=(e&kt)<<14,e<j)||(e=r.get(t+3),n+=(e&kt)<<21,e<j)||(e=r.get(t+4),n+=(e&kt)*lc,e<j)||(e=r.get(t+5),n+=(e&kt)*uc,e<j)||(e=r.get(t+6),n+=(e&kt)*fc,e<j)||(e=r.get(t+7),n+=(e&kt)*hc,e<j))return n;throw new RangeError("Could not decode varint")}function Ct(r,t,e=0){return t==null&&(t=It(ht(r))),t instanceof Uint8Array?dc(r,t,e):$g(r,t,e)}function se(r,t=0){return r instanceof Uint8Array?pc(r,t):Kg(r,t)}var mc=new Float32Array([-0]),We=new Uint8Array(mc.buffer);function Af(r,t,e){mc[0]=r,t[e]=We[0],t[e+1]=We[1],t[e+2]=We[2],t[e+3]=We[3]}function Sf(r,t){return We[0]=r[t],We[1]=r[t+1],We[2]=r[t+2],We[3]=r[t+3],mc[0]}var gc=new Float64Array([-0]),Tt=new Uint8Array(gc.buffer);function _f(r,t,e){gc[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Bf(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],gc[0]}var qg=BigInt(Number.MAX_SAFE_INTEGER),zg=BigInt(Number.MIN_SAFE_INTEGER),Gt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return dr;if(t<qg&&t>zg)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>If&&(o=0n,++n>If&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return dr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):dr}},dr=new Gt(0,0);dr.toBigInt=function(){return 0n};dr.zzEncode=dr.zzDecode=function(){return this};dr.length=function(){return 1};var If=4294967296n;function kf(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Cf(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function yc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ie(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function os(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var wc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ie(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ie(this,4);return os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ie(this,4);return os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ie(this,4);let t=Sf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ie(this,4);let t=Bf(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ie(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Cf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ie(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ie(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Gt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ie(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ie(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ie(this,8);let t=os(this.buf,this.pos+=4),e=os(this.buf,this.pos+=4);return new Gt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=pc(this.buf,this.pos);return this.pos+=ht(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function bc(r){return new wc(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=bc(r);return t.decode(n,void 0,e)}var xc={};Rt(xc,{base10:()=>Gg});var Gg=Ve({prefix:"9",name:"base10",alphabet:"0123456789"});var vc={};Rt(vc,{base16:()=>Wg,base16upper:()=>jg});var Wg=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jg=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ec={};Rt(Ec,{base2:()=>Zg});var Zg=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ac={};Rt(Ac,{base256emoji:()=>t0});var Lf=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Xg=Lf.reduce((r,t,e)=>(r[e]=t,r),[]),Yg=Lf.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Jg(r){return r.reduce((t,e)=>(t+=Xg[e],t),"")}function Qg(r){let t=[];for(let e of r){let n=Yg[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var t0=Ur({prefix:"\u{1F680}",name:"base256emoji",encode:Jg,decode:Qg});var Sc={};Rt(Sc,{base36:()=>e0,base36upper:()=>r0});var e0=Ve({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),r0=Ve({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ic={};Rt(Ic,{base64:()=>_c,base64pad:()=>n0,base64url:()=>Bc,base64urlpad:()=>o0});var _c=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),n0=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bc=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o0=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var kc={};Rt(kc,{base8:()=>s0});var s0=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Cc={};Rt(Cc,{identity:()=>i0});var i0=Ur({prefix:"\0",name:"identity",encode:r=>Fu(r),decode:r=>Ou(r)});var S1=new TextEncoder,_1=new TextDecoder;var Nc={};Rt(Nc,{sha256:()=>Wr,sha512:()=>l0});function Lc({name:r,code:t,encode:e}){return new Tc(r,t,e)}var Tc=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?te(this.code,e):e.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pf(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Wr=Lc({name:"sha2-256",code:18,encode:Pf("SHA-256")}),l0=Lc({name:"sha2-512",code:19,encode:Pf("SHA-512")});var Un={...Cc,...Ec,...kc,...xc,...vc,...Ha,...Sc,...Va,...Ic,...Ac},U1={...Nc,...qa};function Df(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Rf=Df("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Pc=Df("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=It(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),u0={utf8:Rf,"utf-8":Rf,hex:Un.base16,latin1:Pc,ascii:Pc,binary:Pc,...Un},ss=u0;function P(r,t="utf8"){let e=ss[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Rc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return It(i);o+i>t&&(n=It(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var pr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Dc(){}var Uc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},f0=Rc();function h0(r){return globalThis.Buffer!=null?It(r):f0(r)}var Fn=class{len;head;tail;states;constructor(){this.len=0,this.head=new pr(Dc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new pr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Oc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(is,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(is,e.length(),e)}uint64Number(t){return this._push(dc,ht(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Gt.fromBigInt(t).zzEncode();return this._push(is,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(is,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Mc,1,t?1:0)}fixed32(t){return this._push(On,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(On,4,e.lo)._push(On,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(On,4,e.lo)._push(On,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Af,4,t)}double(t){return this._push(_f,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Mc,1,0):this.uint32(e)._push(p0,e,t)}string(t){let e=kf(t);return e!==0?this.uint32(e)._push(yc,e,t):this._push(Mc,1,0)}fork(){return this.states=new Uc(this),this.head=this.tail=new pr(Dc,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(Dc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=h0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Mc(r,t,e){t[e]=r&255}function d0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Oc=class extends pr{next;constructor(t,e){super(d0,t,e),this.next=void 0}};function is(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function On(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function p0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Fn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(m0,t,r),this},Fn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(g0,t,r),this});function m0(r,t,e){t.set(r,e)}function g0(r,t,e){r.length<40?yc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function Fc(){return new Fn}function Mt(r,t){let e=Fc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var jr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(jr||(jr={}));function as(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Vc(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return as("enum",jr.VARINT,e,n)}function Ut(r,t){return as("message",jr.LENGTH_DELIMITED,r,t)}var mr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Vn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var gt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(gt||(gt={}));var Hc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(Hc||(Hc={}));(function(r){r.codec=()=>Vc(Hc)})(gt||(gt={}));var he;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),gt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=gt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(he||(he={}));var $c;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),gt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=gt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})($c||($c={}));var Yn={};Rt(Yn,{MAX_RSA_KEY_SIZE:()=>Js,generateRSAKeyPair:()=>Qc,jwkToJWKKeyPair:()=>Nh,jwkToPkcs1:()=>N0,jwkToPkix:()=>Yc,jwkToRSAPrivateKey:()=>Lh,pkcs1ToJwk:()=>kh,pkcs1ToRSAPrivateKey:()=>Th,pkixToJwk:()=>Ch,pkixToRSAPublicKey:()=>Jc});var y0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),je=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ze=new Uint32Array(64),Kc=class extends zr{constructor(){super(64,32,8,!1),this.A=je[0]|0,this.B=je[1]|0,this.C=je[2]|0,this.D=je[3]|0,this.E=je[4]|0,this.F=je[5]|0,this.G=je[6]|0,this.H=je[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)Ze[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Ze[l-15],h=Ze[l-2],p=re(d,7)^re(d,18)^d>>>3,m=re(h,17)^re(h,19)^h>>>10;Ze[l]=m+Ze[l-7]+p+Ze[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=re(a,6)^re(a,11)^re(a,25),h=f+d+rf(a,c,u)+y0[l]+Ze[l]|0,m=(re(n,2)^re(n,13)^re(n,22))+nf(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Zr=Go(()=>new Kc);var q=sr(Uf());function gr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Xe(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*t);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function us(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function zc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=gr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,gr(s,8)-n}function Of(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=Xe(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Xe(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ff(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function qt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var wv=Math.log(2);function fs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Gc(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Pe(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var $n=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Gc(this.items)}},Hn=[new Uint8Array([1])],Vf="0123456789";var tn="",ae=new ArrayBuffer(0),Wc=new Uint8Array(0),Kn="EndOfContent",$f="OCTET STRING",Kf="BIT STRING";function Re(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):Wc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Pe(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ae)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Te=class{constructor({blockLength:t=0,error:e=tn,warnings:n=[],valueBeforeDecode:o=Wc}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Te.NAME="baseBlock";var Lt=class extends Te{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var hs=class extends Re(Te){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?q.BufferSourceConverter.toUint8Array(t.valueHex):Wc,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",ae}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Xe(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};hs.NAME="identificationBlock";var ds=class extends Te{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=gr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Xe(this.length,8);if(o.byteLength>127)return this.error="Too big length",ae;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ds.NAME="lengthBlock";var C={},At=class extends Te{constructor({name:t=tn,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new hs(o),this.lenBlock=new ds(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new $n;e||qf(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?ae:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Ff(e,n)}};At.NAME="BaseBlock";function qf(r){if(r instanceof C.Constructed)for(let t of r.valueBlock.value)qf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ps=class extends At{constructor({value:t=tn,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ps.NAME="BaseStringBlock";var ms=class extends Re(Lt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};ms.NAME="PrimitiveValueBlock";var zf,gs=class extends At{constructor(t={}){super(t,ms),this.idBlock.isConstructed=!1}};zf=gs;C.Primitive=zf;gs.NAME="PRIMITIVE";function B0(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Xs(r,t=0,e=r.length){let n=t,o=new At({},Lt),s=new Te;if(!Pe(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=At;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=B0(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function jc(r){if(!r.byteLength){let t=new At({},Lt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Xs(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function I0(r,t){return r?1:t}var de=class extends Lt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;I0(this.isIndefiniteForm,n)>0;){let i=Xs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Kn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Kn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new $n;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ae:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};de.NAME="ConstructedValueBlock";var Gf,Ye=class extends At{constructor(t={}){super(t,de),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
3
3
  `).map(o=>` ${o}`).join(`
4
- `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
- ${e.join(`
6
- `)}`:`${t} :`}};vf=er;C.Constructed=vf;er.NAME="CONSTRUCTED";var is=class extends Pe{fromBER(e,t,n){return t}toBER(e){return ht}};is.override="EndOfContentValueBlock";var _f,as=class extends Ie{constructor(e={}){super(e,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_f=as;C.EndOfContent=_f;as.NAME=Gn;var Af,tr=class extends Ie{constructor(e={}){super(e,Pe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Af=tr;C.Null=Af;tr.NAME="NULL";var cs=class extends Ut(Pe){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 Ot(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="BooleanValueBlock";var Sf,ls=class extends Ie{constructor(e={}){super(e,cs),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}`}};Sf=ls;C.Boolean=Sf;ls.NAME="BOOLEAN";var us=class extends Ut(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===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==wf)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}}};us.NAME="OctetStringValueBlock";var Rf,Dt=class r extends Ie{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},us),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=Ms(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?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};Rf=Dt;C.OctetString=Rf;Dt.NAME=wf;var fs=class extends Ut(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===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==bf)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(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ms(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}}};fs.NAME="BitStringValueBlock";var If,sn=class extends Ie{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},fs),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 er.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)}`}}};If=sn;C.BitString=If;sn.NAME=bf;var Tf;function a0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let p=f;p>=0;p--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=Jo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Jo(t,s)),s}function yf(r){if(r>=qn.length)for(let e=qn.length;e<=r;e++){let t=new Uint8Array([0]),n=qn[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=Jo(t,n)),qn.push(n)}return qn[r]}function c0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Yn=class extends Ut(Pe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=yc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(pf(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=c0(yf(n),t),i="-";break;default:t=a0(t,yf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=gf.charAt(t[c]));return a===!1&&(i+=gf.charAt(0)),i}};Tf=Yn;Yn.NAME="IntegerValueBlock";Object.defineProperty(Tf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Bf,pe=class r extends Ie{constructor(e={}){super(e,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return es(),BigInt(this.valueBlock.toString())}static fromBigInt(e){es();let t=BigInt(e),n=new zn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Bf=pe;C.Integer=Bf;pe.NAME="INTEGER";var Cf,hs=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Cf=hs;C.Enumerated=Cf;hs.NAME="ENUMERATED";var Wn=class extends Ut(Pe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){es();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(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=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Wn.NAME="sidBlock";var ds=class extends Pe{constructor({value:e=an,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ht;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 Wn;if(o>Number.MAX_SAFE_INTEGER){es();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ds.NAME="ObjectIdentifierValueBlock";var kf,ft=class extends Ie{constructor(e={}){super(e,ds),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()}}};kf=ft;C.ObjectIdentifier=kf;ft.NAME="OBJECT IDENTIFIER";var jn=class extends Ut(Lt){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(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(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=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var ps=class extends Pe{constructor({value:e=an,...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 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 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}};ps.NAME="RelativeObjectIdentifierValueBlock";var Nf,ms=class extends Ie{constructor(e={}){super(e,ps),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()}}};Nf=ms;C.RelativeObjectIdentifier=Nf;ms.NAME="RelativeObjectIdentifier";var Lf,_e=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Lf=_e;C.Sequence=Lf;_e.NAME="SEQUENCE";var Df,gs=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Df=gs;C.Set=Df;gs.NAME="SET";var ys=class extends Ut(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=an}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="StringValueBlock";var ws=class extends ys{};ws.NAME="SimpleStringValueBlock";var Ke=class extends ns{constructor({...e}={}){super(e,ws)}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}};Ke.NAME="SIMPLE STRING";var bs=class extends Ke{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}};bs.NAME="Utf8StringValueBlock";var Pf,Pt=class extends bs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Pf=Pt;C.Utf8String=Pf;Pt.NAME="UTF8String";var Es=class extends Ke{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))}};Es.NAME="BmpStringValueBlock";var Of,xs=class extends Es{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Of=xs;C.BmpString=Of;xs.NAME="BMPString";var vs=class extends Ke{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Jt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};vs.NAME="UniversalStringValueBlock";var Uf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Uf=_s;C.UniversalString=Uf;_s.NAME="UniversalString";var Mf,As=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Mf=As;C.NumericString=Mf;As.NAME="NumericString";var Ff,Ss=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Ff=Ss;C.PrintableString=Ff;Ss.NAME="PrintableString";var Vf,Rs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Vf=Rs;C.TeletexString=Vf;Rs.NAME="TeletexString";var Kf,Is=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Kf=Is;C.VideotexString=Kf;Is.NAME="VideotexString";var Hf,Ts=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Hf=Ts;C.IA5String=Hf;Ts.NAME="IA5String";var $f,Bs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};$f=Bs;C.GraphicString=$f;Bs.NAME="GraphicString";var qf,Xn=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};qf=Xn;C.VisibleString=qf;Xn.NAME="VisibleString";var zf,Cs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};zf=Cs;C.GeneralString=zf;Cs.NAME="GeneralString";var Gf,ks=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Gf=ks;C.CharacterString=Gf;ks.NAME="CharacterString";var Yf,Zn=class extends Xn{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]=Ge(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Ge(this.month,2),t[2]=Ge(this.day,2),t[3]=Ge(this.hour,2),t[4]=Ge(this.minute,2),t[5]=Ge(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}}};Yf=Zn;C.UTCTime=Yf;Zn.NAME="UTCTime";var Wf,Ns=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,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),l=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(h.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,h.length===4){if(d=parseInt(h.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Ge(this.year,4)),t.push(Ge(this.month,2)),t.push(Ge(this.day,2)),t.push(Ge(this.hour,2)),t.push(Ge(this.minute,2)),t.push(Ge(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Ge(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Wf=Ns;C.GeneralizedTime=Wf;Ns.NAME="GeneralizedTime";var jf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};jf=Ls;C.DATE=jf;Ls.NAME="DATE";var Xf,Ds=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Xf=Ds;C.TimeOfDay=Xf;Ds.NAME="TimeOfDay";var Zf,Ps=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Zf=Ps;C.DateTime=Zf;Ps.NAME="DateTime";var Qf,Os=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Qf=Os;C.Duration=Qf;Os.NAME="Duration";var Jf,Us=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Jf=Us;C.TIME=Jf;Us.NAME="TIME";function u0(r){let{result:e}=cn(r),t=e.valueBlock.value;return{n:F(Et(t[1].toBigInt()),"base64url"),e:F(Et(t[2].toBigInt()),"base64url"),d:F(Et(t[3].toBigInt()),"base64url"),p:F(Et(t[4].toBigInt()),"base64url"),q:F(Et(t[5].toBigInt()),"base64url"),dp:F(Et(t[6].toBigInt()),"base64url"),dq:F(Et(t[7].toBigInt()),"base64url"),qi:F(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function f0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _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 h0(r){let{result:e}=cn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:F(Et(t[0].toBigInt()),"base64url"),e:F(Et(t[1].toBigInt()),"base64url")}}function d0(r){if(r.n==null||r.e==null)throw new E("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 tr]}),new sn({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 p0=16,Ec=32,xc=1e4;async function m0(r,e){let t=Ue.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new tr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=et(p0),a=await mc(On,e,i,{c:xc,dkLen:Ec}),c=et(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 Dt({valueHex:i}),new pe({value:xc}),new pe({value:Ec}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new tr]})]}),p=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 Dt({valueHex:c})]})]})]}),d=new _e({value:[p,new Dt({valueHex:f})]}).toBER(),m=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...F(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function g0(r,e){let t=Ue.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}=cn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=y0(s),l=await mc(On,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Qn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=cn(h);n=eh(d)}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}=cn(o);n=eh(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return vc(n)}function y0(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new E("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Qn(s.valueBlock.value[0].getValue()),a=xc,c=Ec;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new E("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new E("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Qn(u.valueBlock.value[1].getValue());return{cipherText:Qn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function eh(r){return Qn(r.valueBlock.value[2].getValue())}function Qn(r){return new Uint8Array(r,0,r.byteLength)}async function th(r){let e=await Ue.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 oh(e);return{privateKey:t[0],publicKey:t[1]}}async function _c(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await w0(r)],n=await oh({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function rh(r,e){let t=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function nh(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function oh(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)])}async function w0(r){return Ue.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 Fs(r){if(r.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return L(r.n,"base64url").length*8}var eo=8192,Jn=class{_key;constructor(e){this._key=e}verify(e,t){return nh(this._key,t,e)}marshal(){return rr.jwkToPkix(this._key)}get bytes(){return yt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},ln=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return et(16)}sign(e){return rh(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Jn(this._publicKey)}marshal(){return rr.jwkToPkcs1(this._key)}get bytes(){return wt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return rr.exportToPem(this,e);if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function vc(r){let e=rr.pkcs1ToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await _c(e);return new ln(t.privateKey,t.publicKey)}function E0(r){let e=rr.pkixToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Jn(e)}async function x0(r){if(Fs(r)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await _c(r);return new ln(e.privateKey,e.publicKey)}async function v0(r){if(r>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await th(r);return new ln(e.privateKey,e.publicKey)}var Bc={};ve(Bc,{Secp256k1PrivateKey:()=>ro,Secp256k1PublicKey:()=>to,generateKeyPair:()=>P0,unmarshalSecp256k1PrivateKey:()=>L0,unmarshalSecp256k1PublicKey:()=>D0});var _0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),Sc=class extends Zr{constructor(){super(64,32,8,!1),this.A=nr[0]|0,this.B=nr[1]|0,this.C=nr[2]|0,this.D=nr[3]|0,this.E=nr[4]|0,this.F=nr[5]|0,this.G=nr[6]|0,this.H=nr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=or[l-15],h=or[l-2],d=it(p,7)^it(p,18)^p>>>3,m=it(h,17)^it(h,19)^h>>>10;or[l]=m+or[l-7]+d+or[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let p=it(a,6)^it(a,11)^it(a,25),h=f+p+Ou(a,c,u)+_0[l]+or[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Uu(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var sh=Uo(()=>new Sc);function ih(r){r.lowS!==void 0&&at("lowS",r.lowS),r.prehash!==void 0&&at("prehash",r.prehash)}function A0(r){let e=Fn(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:S0,hexToBytes:R0}=Vo,Rr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Rr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:S0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?R0(r):r;Qr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(t.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},sr=BigInt(0),Ae=BigInt(1),j1=BigInt(2),ah=BigInt(3),X1=BigInt(4);function I0(r){let e=A0(r),{Fp:t}=e,n=e.toBytes||((d,m,w)=>{let g=m.toAffine();return Ct(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(d=>{let m=d.subarray(1),w=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:w,y:g}});function s(d){let{a:m,b:w}=e,g=t.sqr(d),y=t.mul(g,d);return t.add(t.add(y,t.mul(d,m)),w)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return Un(d,Ae,e.n)}function a(d){let{allowedPrivateKeyLengths:m,nByteLength:w,wrapPrivateKey:g,n:y}=e;if(m&&typeof d!="bigint"){if(jt(d)&&(d=Tt(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(w*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(le("private key",d,w))}catch{throw new Error(`private key must be ${w} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=X(b,y)),qe("private key",b,Ae,y),b}function c(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}let u=br((d,m)=>{let{px:w,py:g,pz:y}=d;if(t.eql(y,t.ONE))return{x:w,y:g};let b=d.is0();m==null&&(m=b?t.ONE:t.inv(y));let x=t.mul(w,m),A=t.mul(g,m),R=t.mul(y,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x,y:A}}),f=br(d=>{if(d.is0()){if(e.allowInfinityPoint&&!t.is0(d.py))return;throw new Error("bad point: ZERO")}let{x:m,y:w}=d.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not FE");let g=t.sqr(w),y=s(m);if(!t.eql(g,y))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class l{constructor(m,w,g){if(this.px=m,this.py=w,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required");Object.freeze(this)}static fromAffine(m){let{x:w,y:g}=m||{};if(!m||!t.isValid(w)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let y=b=>t.eql(b,t.ZERO);return y(w)&&y(g)?l.ZERO:new l(w,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let w=t.invertBatch(m.map(g=>g.pz));return m.map((g,y)=>g.toAffine(w[y])).map(l.fromAffine)}static fromHex(m){let w=l.fromAffine(o(le("pointHex",m)));return w.assertValidity(),w}static fromPrivateKey(m){return l.BASE.multiply(a(m))}_setWindowSize(m){h.setWindowSize(this,m)}assertValidity(){f(this)}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.eql(t.mul(w,A),t.mul(b,y)),_=t.eql(t.mul(g,A),t.mul(x,y));return R&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:w}=e,g=t.mul(w,ah),{px:y,py:b,pz:x}=this,A=t.ZERO,R=t.ZERO,_=t.ZERO,I=t.mul(y,y),$=t.mul(b,b),V=t.mul(x,x),K=t.mul(y,b);return K=t.add(K,K),_=t.mul(y,x),_=t.add(_,_),A=t.mul(m,_),R=t.mul(g,V),R=t.add(A,R),A=t.sub($,R),R=t.add($,R),R=t.mul(A,R),A=t.mul(K,A),_=t.mul(g,_),V=t.mul(m,V),K=t.sub(I,V),K=t.mul(m,K),K=t.add(K,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,V),I=t.mul(I,K),R=t.add(R,I),V=t.mul(b,x),V=t.add(V,V),I=t.mul(V,K),A=t.sub(A,I),_=t.mul(V,$),_=t.add(_,_),_=t.add(_,_),new l(A,R,_)}add(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.ZERO,_=t.ZERO,I=t.ZERO,$=e.a,V=t.mul(e.b,ah),K=t.mul(w,b),Q=t.mul(g,x),D=t.mul(y,A),N=t.add(w,g),S=t.add(b,x);N=t.mul(N,S),S=t.add(K,Q),N=t.sub(N,S),S=t.add(w,y);let v=t.add(b,A);return S=t.mul(S,v),v=t.add(K,D),S=t.sub(S,v),v=t.add(g,y),R=t.add(x,A),v=t.mul(v,R),R=t.add(Q,D),v=t.sub(v,R),I=t.mul($,S),R=t.mul(V,D),I=t.add(R,I),R=t.sub(Q,I),I=t.add(Q,I),_=t.mul(R,I),Q=t.add(K,K),Q=t.add(Q,K),D=t.mul($,D),S=t.mul(V,S),Q=t.add(Q,D),D=t.sub(K,D),D=t.mul($,D),S=t.add(S,D),K=t.mul(Q,S),_=t.add(_,K),K=t.mul(v,S),R=t.mul(N,R),R=t.sub(R,K),K=t.mul(N,Q),I=t.mul(v,I),I=t.add(I,K),new l(R,_,I)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,m,l.normalizeZ)}multiplyUnsafe(m){qe("scalar",m,sr,e.n);let w=l.ZERO;if(m===sr)return w;if(m===Ae)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:y,k1:b,k2neg:x,k2:A}=g.splitScalar(m),R=w,_=w,I=this;for(;b>sr||A>sr;)b&Ae&&(R=R.add(I)),A&Ae&&(_=_.add(I)),I=I.double(),b>>=Ae,A>>=Ae;return y&&(R=R.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),R.add(_)}multiply(m){let{endo:w,n:g}=e;qe("scalar",m,Ae,g);let y,b;if(w){let{k1neg:x,k1:A,k2neg:R,k2:_}=w.splitScalar(m),{p:I,f:$}=this.wNAF(A),{p:V,f:K}=this.wNAF(_);I=h.constTimeNegate(x,I),V=h.constTimeNegate(R,V),V=new l(t.mul(V.px,w.beta),V.py,V.pz),y=I.add(V),b=$.add(K)}else{let{p:x,f:A}=this.wNAF(m);y=x,b=A}return l.normalizeZ([y,b])[0]}multiplyAndAddUnsafe(m,w,g){let y=l.BASE,b=(A,R)=>R===sr||R===Ae||!A.equals(y)?A.multiplyUnsafe(R):A.multiply(R),x=b(this,w).add(b(m,g));return x.is0()?void 0:x}toAffine(m){return u(this,m)}isTorsionFree(){let{h:m,isTorsionFree:w}=e;if(m===Ae)return!0;if(w)return w(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:w}=e;return m===Ae?this:w?w(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return at("isCompressed",m),this.assertValidity(),n(l,this,m)}toHex(m=!0){return at("isCompressed",m),Tt(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=$o(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function T0(r){let e=Fn(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ch(r){let e=T0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(N){return X(N,n)}function a(N){return Ko(N,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=I0({...e,toBytes(N,S,v){let T=S.toAffine(),B=t.toBytes(T.x),P=Ct;return at("isCompressed",v),v?P(Uint8Array.from([S.hasEvenY()?2:3]),B):P(Uint8Array.from([4]),B,t.toBytes(T.y))},fromBytes(N){let S=N.length,v=N[0],T=N.subarray(1);if(S===o&&(v===2||v===3)){let B=Bt(T);if(!Un(B,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(B),O;try{O=t.sqrt(P)}catch(H){let G=H instanceof Error?": "+H.message:"";throw new Error("Point is not on curve"+G)}let U=(O&Ae)===Ae;return(v&1)===1!==U&&(O=t.neg(O)),{x:B,y:O}}else if(S===s&&v===4){let B=t.fromBytes(T.subarray(0,t.BYTES)),P=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:B,y:P}}else throw new Error(`Point of length ${S} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=N=>Tt(Zt(N,e.nByteLength));function h(N){let S=n>>Ae;return N>S}function d(N){return h(N)?i(-N):N}let m=(N,S,v)=>Bt(N.slice(S,v));class w{constructor(S,v,T){this.r=S,this.s=v,this.recovery=T,this.assertValidity()}static fromCompact(S){let v=e.nByteLength;return S=le("compactSignature",S,v*2),new w(m(S,0,v),m(S,v,2*v))}static fromDER(S){let{r:v,s:T}=Rr.toSig(le("DER",S));return new w(v,T)}assertValidity(){qe("r",this.r,Ae,n),qe("s",this.s,Ae,n)}addRecoveryBit(S){return new w(this.r,this.s,S)}recoverPublicKey(S){let{r:v,s:T,recovery:B}=this,P=R(le("msgHash",S));if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");let O=B===2||B===3?v+e.n:v;if(O>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=B&1?"03":"02",z=c.fromHex(U+p(O)),H=a(O),G=i(-P*H),oe=i(T*H),se=c.BASE.multiplyAndAddUnsafe(z,G,oe);if(!se)throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return yr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let g={isValidPrivateKey(N){try{return u(N),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let N=qa(e.n);return Gu(e.randomBytes(N),e.n)},precompute(N=8,S=c.BASE){return S._setWindowSize(N),S.multiply(BigInt(3)),S}};function y(N,S=!0){return c.fromPrivateKey(N).toRawBytes(S)}function b(N){let S=jt(N),v=typeof N=="string",T=(S||v)&&N.length;return S?T===o||T===s:v?T===2*o||T===2*s:N instanceof c}function x(N,S,v=!0){if(b(N))throw new Error("first arg must be private key");if(!b(S))throw new Error("second arg must be public key");return c.fromHex(S).multiply(u(N)).toRawBytes(v)}let A=e.bits2int||function(N){let S=Bt(N),v=N.length*8-e.nBitLength;return v>0?S>>BigInt(v):S},R=e.bits2int_modN||function(N){return i(A(N))},_=Mn(e.nBitLength);function I(N){return qe(`num < 2^${e.nBitLength}`,N,sr,_),Zt(N,e.nByteLength)}function $(N,S,v=V){if(["recovered","canonical"].some(Ee=>Ee in v))throw new Error("sign() legacy options not supported");let{hash:T,randomBytes:B}=e,{lowS:P,prehash:O,extraEntropy:U}=v;P==null&&(P=!0),N=le("msgHash",N),ih(v),O&&(N=le("prehashed msgHash",T(N)));let z=R(N),H=u(S),G=[I(H),I(z)];if(U!=null&&U!==!1){let Ee=U===!0?B(t.BYTES):U;G.push(le("extraEntropy",Ee))}let oe=Ct(...G),se=z;function $e(Ee){let me=A(Ee);if(!l(me))return;let nt=a(me),xe=c.BASE.multiply(me).toAffine(),ot=i(xe.x);if(ot===sr)return;let dr=i(nt*i(se+ot*H));if(dr===sr)return;let Cn=(xe.x===ot?0:2)|Number(xe.y&Ae),Io=dr;return P&&h(dr)&&(Io=d(dr),Cn^=1),new w(ot,Io,Cn)}return{seed:oe,k2sig:$e}}let V={lowS:e.lowS,prehash:!1},K={lowS:e.lowS,prehash:!1};function Q(N,S,v=V){let{seed:T,k2sig:B}=$(N,S,v),P=e;return Va(P.hash.outputLen,P.nByteLength,P.hmac)(T,B)}c.BASE._setWindowSize(8);function D(N,S,v,T=K){let B=N;if(S=le("msgHash",S),v=le("publicKey",v),"strict"in T)throw new Error("options.strict was renamed to lowS");ih(T);let{lowS:P,prehash:O}=T,U,z;try{if(typeof B=="string"||jt(B))try{U=w.fromDER(B)}catch(xe){if(!(xe instanceof Rr.Err))throw xe;U=w.fromCompact(B)}else if(typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint"){let{r:xe,s:ot}=B;U=new w(xe,ot)}else throw new Error("PARSE");z=c.fromHex(v)}catch(xe){if(xe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&U.hasHighS())return!1;O&&(S=e.hash(S));let{r:H,s:G}=U,oe=R(S),se=a(G),$e=i(oe*se),Ee=i(H*se),me=c.BASE.multiplyAndAddUnsafe(z,$e,Ee)?.toAffine();return me?i(me.x)===H:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:x,sign:Q,verify:D,ProjectivePoint:c,Signature:w,utils:g}}function B0(r){return{hash:r,hmac:(e,...t)=>$n(r,e,La(...t)),randomBytes:Xr}}function lh(r,e){let t=n=>ch({...r,...B0(n)});return Object.freeze({...t(e),create:t})}var hh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),C0=BigInt(1),Rc=BigInt(2),fh=(r,e)=>(r+e/Rc)/e;function k0(r){let e=hh,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=te(f,t,e)*f%e,p=te(l,t,e)*f%e,h=te(p,Rc,e)*u%e,d=te(h,o,e)*h%e,m=te(d,s,e)*d%e,w=te(m,a,e)*m%e,g=te(w,c,e)*w%e,y=te(g,a,e)*m%e,b=te(y,t,e)*f%e,x=te(b,i,e)*d%e,A=te(x,n,e)*u%e,R=te(A,Rc,e);if(!Ic.eql(Ic.sqr(R),r))throw new Error("Cannot find square root");return R}var Ic=Ho(hh,void 0,void 0,{sqrt:k0}),dt=lh({a:BigInt(0),b:BigInt(7),Fp:Ic,n:uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=uh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-C0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=fh(s*r,e),c=fh(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,p=f>i;if(l&&(u=e-u),p&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},sh),sv=BigInt(0);var iv=dt.ProjectivePoint;function dh(){return dt.utils.randomPrivateKey()}function ph(r,e){let t=Se.digest(e instanceof Uint8Array?e:e.subarray());if(Je(t))return t.then(({digest:n})=>dt.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return dt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function mh(r,e,t){let n=Se.digest(t instanceof Uint8Array?t:t.subarray());if(Je(n))return n.then(({digest:o})=>dt.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return dt.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function gh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function yh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Tc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function wh(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var to=class{_key;constructor(e){Tc(e),this._key=e}verify(e,t){return mh(this._key,t,e)}marshal(){return gh(this._key)}get bytes(){return yt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}},ro=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??wh(e),yh(this._key),Tc(this._publicKey)}sign(e){return ph(this._key,e)}get public(){return new to(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function L0(r){return new ro(r)}function D0(r){return new to(r)}async function P0(){let r=dh();return new ro(r)}var ir={rsa:Ac,ed25519:pc,secp256k1:Bc};function Cc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function kc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw Cc(r)}async function bh(r,e){return kc(r).generateKeyPair(e??2048)}function no(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPublicKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PublicKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Cc(e.Type??"unknown")}}function Eh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}async function oo(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPrivateKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PrivateKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Cc(e.Type??"RSA")}}function xh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}function O0(r,e){try{if(typeof r=="string"&&r.length>0)return U0(r);if(typeof r=="number"&&isFinite(r))return e?.long?F0(r):M0(r);throw new Error("Value is not a string or number.")}catch(t){let n=V0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function U0(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 Ks=O0;function M0(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 F0(r){let e=Math.abs(r);return e>=864e5?Vs(r,e,864e5,"day"):e>=36e5?Vs(r,e,36e5,"hour"):e>=6e4?Vs(r,e,6e4,"minute"):e>=1e3?Vs(r,e,1e3,"second"):`${r} ms`}function Vs(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function V0(r){return typeof r=="object"&&r!==null&&"message"in r}function Nc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Ks,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let p=0;p<f.length;p++)l=(l<<5)-l+f.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,p=null,h,d;function m(...w){if(!m.enabled)return;let g=m,y=Number(new Date),b=y-(l||y);g.diff=b,g.prev=l,g.curr=y,l=y,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let x=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(R,_)=>{if(R==="%%")return"%";x++;let I=t.formatters[_];if(typeof I=="function"){let $=w[x];R=I.call(g,$),w.splice(x,1),x--}return R}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}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:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,d=t.enabled(f)),d),set:w=>{p=w}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let p=t(this.namespace+(typeof l>"u"?":":l)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(l=0;l<h;l++)p[l]&&(f=p[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.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,p;for(l=0,p=t.skips.length;l<p;l++)if(t.skips[l].test(f))return!1;for(l=0,p=t.names.length;l<p;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Hs=Y0(),K0=["#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 H0(){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 $0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ks(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 q0=console.debug??console.log??(()=>{});function z0(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function G0(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Y0(){try{return localStorage}catch{}}function W0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var vh=Nc({formatArgs:$0,save:z0,load:G0,useColors:H0,setupFormatters:W0,colors:K0,storage:Hs,log:q0});var je=vh;je.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);je.formatters.t=r=>r==null?"undefined":Ye.baseEncode(r);je.formatters.m=r=>r==null?"undefined":Dn.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 j0(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 $s(){return{forComponent(r){return X0(r)}}}function X0(r){let e=j0(`${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})}var Ah=Symbol.for("nodejs.util.inspect.custom"),_h=Object.values(zt).map(r=>r.decoder).reduce((r,e)=>r.or(e),zt.identity.decoder),Sh=114,Pc=36,Oc=37,so=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()})`}[Bo]=!0;toString(){return this.string==null&&(this.string=ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Qe.createV1(Sh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return J(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Ah](){return`PeerId(${this.toString()})`}},Ir=class extends so{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends so{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends so{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Lc=2336,Dc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Rt.digest(L(this.url))}[Ah](){return`PeerId(${this.url})`}[Bo]=!0;toString(){return this.toCID().toString()}toCID(){return Qe.createV1(Lc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function Rh(r){if(r.type==="RSA")return new Ir(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Br(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??_h,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ae.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Ir({multihash:t})}return un(_h.decode(r))}function un(r){try{let e=mr(r);if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:e});if(e.digest.length===Oc)return new Br({multihash:e})}if(e.code===Se.code)return new Ir({multihash:e})}catch{return Z0(Qe.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Z0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Sh&&r.code!==Lc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Lc){let t=F(r.multihash.digest);return new Dc(new URL(t))}let e=r.multihash;if(e.code===Se.code)return new Ir({multihash:r.multihash});if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:r.multihash});if(e.digest.length===Oc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function fn(r,e){return r.length===Pc?new Tr({multihash:mt(Rt.code,r),privateKey:e}):r.length===Oc?new Br({multihash:mt(Rt.code,r),privateKey:e}):new Ir({multihash:await Se.digest(r),publicKey:r,privateKey:e})}function hn(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 Xe=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 hn(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 hn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var Mt=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 hn(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 hn(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 kh=Symbol.for("@achingbrain/uint8arraylist");function Ch(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 zs(r){return!!r?.[kh]}var we=class r{bufs;length;[kh]=!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(zs(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(zs(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=Ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ch(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(zs(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 Re(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Re(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(!zs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let p=u;p>=0;p--){let h=this.get(l+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=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=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=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=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(!J(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 Uc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Uc)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?J(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var kr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof 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=Cr(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 Mc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Lh=new globalThis.TextEncoder;function Q0(r,e){let t=Mc[e],n=Nh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function J0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Mc[e],o=Nh[e],s=r;for(;s.length>0;){let i=Lh.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 Fc(r,{size:e=32,utf8Buffer:t}={}){if(!Mc[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 J0(r,e,t);r=Lh.encode(r)}return Q0(r,e)}var ey=pr(Bh(),1);var ao={hash:r=>Number(Fc(r,{size:32})),hashV:(r,e)=>ty(ao.hash(r,e))};function ty(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var ry=500,co=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??ao,this.seed=e.seed??Cr(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 kr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new kr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize));for(let a=0;a<ry;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=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}},ny={1:.5,2:.84,4:.95,8:.98};function oy(r=.001){return r>.002?2:r>1e-5?4:8}function Dh(r,e=.001){let t=oy(e),n=ny[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Uc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Gs=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??ao,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new co({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 co({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 Vc(r,e=.001,t){return new Gs({...Dh(r,e),...t??{}})}var Ph=async()=>{let r=await bh("Ed25519"),e=await sy(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function sy(r){return fn(Eh(r.public),xh(r))}var Oh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var lo;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((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=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(lo||(lo={}));var dn=class r{static createFromProtobuf=async e=>{let t=lo.decode(e),n=await fn(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=Uh(n,o,s),c=await(await oo(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new E("envelope signature is not valid for the given domain",Oh.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=lo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return J(this.marshal(),e.marshal())}async validate(e){let t=Uh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return no(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Uh=(r,e,t)=>{let n=L(r),o=Le(n.byteLength),s=Le(e.length),i=Le(t.length);return new we(o,n,s,e,i,t)};function Mh(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 Ys=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Fh=45,iy=15,pn=new Ys;function Kc(r){if(!(r.length>iy))return pn.new(r).parseWith(()=>pn.readIPv4Addr())}function Hc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPv6Addr())}function Ws(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPAddr())}var sA=parseInt("0xFFFF",16),iA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function mn(r){return!!Kc(r)}function gn(r){return!!Hc(r)}function js(r){return!!Ws(r)}var Hh=mn,fy=gn,$c=function(r){let e=0;if(r=r.toString().trim(),Hh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(fy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Hh(t[n]),i;s&&(i=$c(t[n]),t[n]=F(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(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")},$h=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 yn={},qc={},dy=[[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"]];dy.forEach(r=>{let e=py(...r);qc[e.code]=e,yn[e.name]=e});function py(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function j(r){if(typeof r=="number"){if(qc[r]!=null)return qc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yn[r]!=null)return yn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var $A=j("ip4"),qA=j("ip6"),zA=j("ipcidr");function Wc(r,e){switch(j(r).code){case 4:case 41:return gy(e);case 42:return Yc(e);case 6:case 273:case 33:case 132:return Gh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Yc(e);case 421:return Ey(e);case 444:return zh(e);case 445:return zh(e);case 466:return by(e);case 481:return globalThis.encodeURIComponent(Yc(e));default:return F(e,"base16")}}function jc(r,e){switch(j(r).code){case 4:return qh(e);case 41:return qh(e);case 42:return Gc(e);case 6:case 273:case 33:case 132:return Xc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gc(e);case 421:return yy(e);case 444:return xy(e);case 445:return vy(e);case 466:return wy(e);case 481:return Gc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var zc=Object.values(zt).map(r=>r.decoder),my=function(){let r=zc[0].or(zc[1]);return zc.slice(2).forEach(e=>r=r.or(e)),r}();function qh(r){if(!js(r))throw new Error("invalid ip address");return $c(r)}function gy(r){let e=$h(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!js(e))throw new Error("invalid ip address");return e}function Xc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Gh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gc(r){let e=L(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function Yc(r){let e=lt(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function yy(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ae.decode(`z${r}`)).bytes:e=Qe.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function wy(r){let e=my.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function by(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function Ey(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function xy(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=Ye.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=Xc(n);return Re([t,o],t.length+o.length)}function vy(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=Ye.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=Xc(n);return Re([t,o],t.length+o.length)}function zh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Gh(t);return`${n}:${o}`}function Yh(r){r=Zc(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=j(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw jh("invalid address: "+r);if(a.path===!0){n=Zc(o.slice(s).join("/")),e.push([a.code,jc(a.code,n)]),t.push([a.code,n]);break}let c=jc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Wc(a.code,c)])}return{string:Wh(t),bytes:Jc(e),tuples:e,stringTuples:t,path:n}}function Qc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=de(s),a=j(s),c=_y(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 jh("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=Wc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Wh(t),tuples:e,stringTuples:t,path:n}}function Wh(r){let e=[];return r.map(t=>{let n=j(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Zc(e.join("/"))}function Jc(r){return Re(r.map(e=>{let t=j(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function _y(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 Zc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function jh(r){return new Error("Error parsing address: "+r)}var Ay=Symbol.for("nodejs.util.inspect.custom"),el=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Sy=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Xs=class r{bytes;#e;#t;#s;#a;[el]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Qc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Yh(e)}else if(ar(e))t=Qc(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=j("tcp"),a=j("udp"),c=j("ip4"),u=j("ip6"),f=j("dns6"),l=j("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),Sy.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=j(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=j(h).name,n=`${d??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},j(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>j(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(Jc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===yn.p2p.code&&e.push([n,o]),n===yn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?F(ae.decode(`z${n}`),"base58btc"):F(Qe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return J(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=wn.get(t.name);if(n==null)throw new E(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>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)}[Ay](){return`Multiaddr(${this.#e})`}};var wn=new Map;function ar(r){return!!r?.[el]}function ne(r){return new Xs(r)}var Xh="libp2p-peer-record",Zh=Uint8Array.from([3,1]);var uo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ve((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=>Fe(s,n.codec()),n.decode=s=>Me(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ve((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=>Fe(n,r.codec()),r.decode=n=>Me(n,r.codec())})(uo||(uo={}));var Nr=class r{static createFromProtobuf=e=>{let t=uo.decode(e),n=un(t.peerId),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xh;static CODEC=Zh;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=uo.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||!Mh(this.multiaddrs,e.multiaddrs))}};function Ry(r){return r[Symbol.asyncIterator]!=null}function Iy(r){if(Ry(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 fo=Iy;var rl=pr(Jh(),1);var po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},nl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ed=r=>globalThis.DOMException===void 0?new nl(r):new DOMException(r),td=r=>{let e=r.reason===void 0?ed("This operation was aborted."):r.reason;return e instanceof Error?e:ed(e)};function mo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(td(p)),p.addEventListener("abort",()=>{f(td(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new po;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function ol(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var go=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=ol(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 cr=class extends rl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:go,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#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=mo(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 po&&!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 lr={},bn=r=>{r.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)})};bn.addEventListener=(r,e)=>{lr[r]==null&&(lr[r]=[]),lr[r].push(e)};bn.removeEventListener=(r,e)=>{lr[r]!=null&&(lr[r]=lr[r].filter(t=>t===e))};bn.dispatchEvent=function(r,e,t){lr[r]!=null&&lr[r].forEach(n=>n(e,t))};var sl=bn;var il="lock:worker:request-read",al="lock:worker:release-read",cl="lock:master:grant-read",ll="lock:worker:request-write",ul="lock:worker:release-write",fl="lock:master:grant-write";var rd=(r=21)=>Math.random().toString().substring(2);var nd=(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)})}}}))},od=(r,e,t,n)=>async()=>{let o=rd();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)})},Cy={singleProcess:!1},sd=r=>{if(r=Object.assign({},Cy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return sl.addEventListener("message",nd(t,"requestReadLock",il,al,cl)),sl.addEventListener("message",nd(t,"requestWriteLock",ll,ul,fl)),t}return{isWorker:!0,readLock:t=>od(t,il,cl,al),writeLock:t=>od(t,ll,fl,ul)}};var Lr={},ur;async function hl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var ky=(r,e)=>{if(ur.isWorker===!0)return{readLock:ur.readLock(r,e),writeLock:ur.writeLock(r,e)};let t=new cr({concurrency:1}),n;return{async readLock(){if(n!=null)return hl(n,e);n=new cr({concurrency:e.concurrency,autoStart:!1});let o=n,s=hl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,hl(t,e)}}},Ny={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function dl(r){let e=Object.assign({},Ny,r);return ur==null&&(ur=sd(e),ur.isWorker!==!0&&(ur.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ur.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=ky(e.name,e)),Lr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var En;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((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=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((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),Js.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=Js.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ve((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Qs.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(Qs.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=>Fe(o,r.codec()),r.decode=o=>Me(o,r.codec())})(En||(En={}));var Qs;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((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=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Qs||(Qs={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((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=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Js||(Js={}));function xn(r,e){let t=En.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Rh({...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:ne(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",id=new TextEncoder().encode(Ft),ei=id[0],Dr=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]!==ei)throw new Error("Invalid key")}toString(e="utf8"){return F(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=id),this._buf[0]!==ei){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ei,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ei;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return Ly(this.baseNamespace())}name(){return Dy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Py(e.map(t=>t.namespaces()))])}};function Ly(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Dy(r){let e=r.split(":");return e[e.length-1]}function Py(r){return[].concat(...r)}var pl="/peers/";function vn(r){if(!Co(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${pl}${e}`)}async function ad(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)),!ar(o.multiaddr))throw new E("Multiaddr was invalid",Te.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function ri(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!J(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",Te.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new E("peer id did not match existing peer id",Te.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ti(l,{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ti(l,{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,h]of l)h==null?a.delete(p):a.set(p,h);a=ti([...a.entries()],{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[h,d]of l)d==null?p.delete(h):p.set(h,d);c=ti([...p.entries()],{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await ad(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,p)=>l.localeCompare(p)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function ti(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 cd(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Te.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Te.ERR_INVALID_PARAMETERS)}function ld(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Te.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Te.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Te.ERR_INVALID_PARAMETERS)}}function ud(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 ni(r,e,t){let n=r.toString().split("/")[2],o=Ye.decode(n),s=un(o),i=t.get(s);if(i!=null)return i;let a=xn(s,e);return t.set(s,a),a}function Oy(r,e){return r==null?{}:{prefix:pl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ni(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ni(n.key,n.value,e),ni(o.key,o.value,e)))}}var oi=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=dl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(vn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(vn(e))}async load(e){let t=await this.datastore.get(vn(e));return xn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(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 ri(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 ri(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(Oy(e??{},t))){let s=ni(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(vn(e)),n=xn(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=En.encode(t);return n!=null&&J(s,n)?{peer:xn(e,s),previous:o,updated:!1}:(await this.datastore.put(vn(e),s),{peer:xn(e,s),previous:o,updated:!0})}};var si=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 oi(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 fo(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 dn.openAndCertify(e,Nr.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=Nr.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 dn.createFromProtobuf(s.peerRecordEnvelope),a=Nr.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 Uy(r){return r[Symbol.asyncIterator]!=null}function My(r){if(Uy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ml=My;function Fy(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 fd=Fy;function Vy(r){return r[Symbol.asyncIterator]!=null}function Ky(r,e){let t=0;if(Vy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=fd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Pr=Ky;function Hy(r){return r[Symbol.asyncIterator]!=null}function $y(r,e){return Hy(r)?async function*(){yield*(await fo(r)).sort(e)}():function*(){yield*fo(r).sort(e)}()}var gl=$y;function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r,e){return qy(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 yl=zy;var ii=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 ml(this.putMany(e,n)),e=[],await ml(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=yl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=yl(n,e.limit)),n}};var md=pr(pd(),1);function gd(r){return r=r??new Error("Not Found"),(0,md.default)(r,"ERR_NOT_FOUND")}var ai=class extends ii{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 gd();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Dr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Dr(e)}};function yd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Wy=r=>r;function wl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var ci=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??Wy,this._updatePeerStoreAddresses=yd(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=wl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=wl(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=wl(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 bl=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=$s())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>fu(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")}},jy=["metrics","connectionProtector","dns"],Xy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function wd(r={}){let e=new bl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Xy.includes(o)){let i=e.components[o];if(i==null&&!jy.includes(o))throw new E(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function bd(r){let e={};for(let t of Object.values(r.components))for(let n of Zy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Qy(t))if(e[n]!==!0)throw new E(`Service "${Jy(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 Zy(r){return Array.isArray(r?.[kn])?r[kn]:[]}function Qy(r){return Array.isArray(r?.[ua])?r[ua]:[]}function Jy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var xd=pr(Ed(),1),ew=["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"],tw=ew.map(r=>new xd.Netmask(r));function El(r){for(let e of tw)if(e.contains(r))return!0;return!1}function rw(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function nw(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 El(o)}function ow(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function sw(r){let e=r.split(":"),t=e[e.length-1];return El(t)}function iw(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 li(r){return mn(r)?El(r):rw(r)?nw(r):ow(r)?sw(r):gn(r)?iw(r):void 0}function vd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!li(`${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 aw=r=>r.toString().split("/").slice(1),wo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>wo(t=>t===r).match(e),pattern:r}),hi=()=>({match:r=>wo(e=>typeof e=="string").match(r),pattern:"{string}"}),di=()=>({match:r=>wo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Be=()=>({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}"}),ui=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ia.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})`}),rt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=aw(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 vl=Z(Y("dns4"),hi()),_l=Z(Y("dns6"),hi()),Al=Z(Y("dnsaddr"),hi()),_d=Z(Y("dns"),hi()),gR=fe(vl),yR=fe(_l),wR=fe(Al),bR=fe(rt(_d,Al,vl,_l)),Ad=Z(Y("ip4"),wo(mn)),Sd=Z(Y("ip6"),wo(gn)),Rd=rt(Ad,Sd),vt=rt(Rd,_d,vl,_l,Al),ER=fe(vt),xR=fe(Ad),vR=fe(Sd),_R=fe(Rd),Sl=Z(vt,Y("tcp"),di()),bo=Z(vt,Y("udp"),di()),AR=fe(Sl),SR=fe(bo),Rl=Z(bo,Y("quic")),pi=Z(bo,Y("quic-v1")),cw=rt(Rl,pi),RR=fe(Rl),IR=fe(pi),xl=rt(vt,Sl,bo,Rl,pi),Id=rt(Z(xl,Y("ws"),be(Be()))),TR=fe(Id),Td=rt(Z(xl,Y("wss"),be(Be())),Z(xl,Y("tls"),Y("ws"),be(Be()))),BR=fe(Td),Bd=Z(bo,Y("webrtc-direct"),be(ui()),be(ui()),be(Be())),CR=fe(Bd),Cd=Z(pi,Y("webtransport"),be(ui()),be(ui()),be(Be())),kR=fe(Cd),fi=rt(Id,Td,Z(Sl,be(Be())),Z(cw,be(Be())),Z(vt,be(Be())),Bd,Cd,Be()),NR=fe(fi),lw=Z(fi,Y("p2p-circuit"),Be()),Eo=fe(lw),uw=rt(Z(fi,Y("p2p-circuit"),Y("webrtc"),be(Be())),Z(fi,Y("webrtc"),be(Be())),Y("webrtc")),LR=fe(uw),fw=rt(Z(vt,Y("tcp"),di(),Y("http"),be(Be())),Z(vt,Y("http"),be(Be()))),DR=fe(fw),hw=rt(Z(vt,Y("tcp"),rt(Z(Y("443"),Y("http")),Z(di(),Y("https"))),be(Be())),Z(vt,Y("tls"),Y("http"),be(Be())),Z(vt,Y("https"),be(Be()))),PR=fe(hw);function Il(r){try{let{address:e}=r.nodeAddress();return!!li(e)}catch{return!0}}function dw(r,e){let t=Il(r.multiaddr),n=Il(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function pw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function mw(r,e){let t=Eo.exactMatch(r.multiaddr),n=Eo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _n(r,e){let t=dw(r,e);if(t!==0)return t;let n=mw(r,e);return n!==0?n:pw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function mi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Tl=60;function gi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??Tl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var gw=4;function Bl(r,e={}){let t=new cr({concurrency:e.queryConcurrency??gw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mi(o.types).forEach(a=>{s.append("type",Ze[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=gi(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 kd(){return[Bl("https://cloudflare-dns.com/dns-query"),Bl("https://dns.google/resolve")]}var Dd=pr(Ld(),1);var Cl=class{lru;constructor(e){this.lru=(0,Dd.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 gi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Tl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Pd(r){return new Cl(r)}var yw=1e3,yi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Pd(e.cacheSize??yw),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["."]=kd())}async query(e,t={}){let n=mi(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 Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function Od(r={}){return new yi(r)}var ww=32,{code:bw}=j("dnsaddr"),Or=async function(e,t={}){let n=t.maxRecursiveDepth??ww;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===bw)??[],i=await(t?.dns??Od()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ne(f);if(f.startsWith("/dnsaddr")){let p=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...p.map(h=>h.toString()))}else c.push(l.toString())}return c};var zd=pr(qd(),1),Ei=zd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var 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 Sw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Or},addressSorter:_n},transportManager:{faultTolerance:Ht.FATAL_ALL}};async function Gd(r){let e=Ei(Sw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,k.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await fn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",k.ERR_INVALID_KEY);return e}var Yd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rw=new WeakMap;function Iw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Yd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Yd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((p,h)=>{i=()=>{f(),p(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Rw.set(l,()=>{c(s),s=null,i()}),l}}var Tw=Iw(),Wd=Tw;var xi=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 Nl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new E("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Wd(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)}},Nl=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 vi(r){if(Co(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(!ar(n))throw new E("Invalid Multiaddr",k.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e?.equals(s)!==!0)throw new E("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 _i=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}},Rn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new _i(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 _i(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 Ll=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ai(r={}){return Bw(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 Bw(r,e){e=e??{};let t=e.onEnd,n=new Rn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=y=>{s=null,n.push(y);try{w(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new Rn,s!=null?s({error:w}):(n.push({error:w}),o)),l=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},p=w=>i?o:(i=!0,w!=null?f(w):u({done:!0})),h=()=>(n=new Rn,p(),{done:!0}),d=w=>(p(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:d,push:l,end:p,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let y,b;g!=null&&(y=new Promise((x,A)=>{b=()=>{A(new Ll)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,y])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var Dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function In(r,e,t,n){let o=new Dl(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(p){a(),i(p);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 Si=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 fr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Si(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Si(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 Ri=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 $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Cw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Cw(),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 $t),this.cleanup())}async join(e={}){let t=new Ri(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 fr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Tn=class extends At{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 Ii(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 $t)}),this.clear()}async onEmpty(e){this.size!==0&&await In(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await In(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await In(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=Ai({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new E("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ti=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Bi="last-dial-failure";var Ci=5,ki=100,Ni=50,Li=1e3*60*7;var Ur={minConnections:Ci,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Di=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??Ur.minConnections,this.autoDialPriority=t.autoDialPriority??Ur.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Ur.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Ur.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Ur.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ur.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ti({concurrency:t.autoDialConcurrency??Ur.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 Mt(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 Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,p=i.get(f.id)??0;return l>p?-1:l<p?1:0}).filter(u=>{let f=u.metadata.get(Bi);if(f==null)return!0;let l=parseInt(F(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 Nw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Nw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Xd={maxConnections:ki,allow:[]},Pi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Xd.maxConnections,this.allow=t.allow??Xd.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 Xe;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 jd(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 Oi=class extends Tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Mr(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 Zd(r,e){let t=!1;for(let o of wn.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 xo={addressSorter:_n,maxParallelDials:Ni,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Or}},Ui=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??xo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??xo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??xo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??xo.dialTimeout,this.connections=t.connections??new Xe,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??{}))wn.set(n,o);this.queue=new Oi({concurrency:t.maxParallelDials??xo.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}=vi(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 E("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 p of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new E("Peer had more than maxPeerAddrsToDial",k.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(p.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",p.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",p.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Bi]:L(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new E(h.message,No);l.push(h)}}throw l.length===1?l[0]:new ko(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Hl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Mr([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:ne(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new E("Tried to dial self",k.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("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:p})=>p.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:p})=>p.toString())),o.push(...l.multiaddrs.map(p=>({multiaddr:p,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 p=await Zd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return p.length===1&&p[0].equals(l.multiaddr)?l:p.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(p=>p.multiaddr.protos().pop()?.path===!0?p:p.multiaddr.getPeerId()==null?{multiaddr:p.multiaddr.encapsulate(l),isCertified:p.isCertified}:p)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let p=l.multiaddr.getPeerId();return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let l of i){let p=l.multiaddr.toString(),h=a.get(p);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(p,l)}let c=[...a.values()];if(c.length===0)throw new E("The dial request has no valid addresses",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 E("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=>!Eo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Hl=50,Kt={minConnections:Ci,maxConnections:ki,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Mi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kt.maxConnections;let n=t.minConnections??Kt.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",k.ERR_INVALID_PARAMETERS);this.connections=new Xe,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=>ne(o)),this.deny=(t.deny??[]).map(o=>ne(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new xi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Di({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Kt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Kt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Kt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Kt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Kt.autoDialMaxQueueLength}),this.connectionPruner=new Pi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ui(e,{addressSorter:t.addressSorter??_n,maxParallelDials:t.maxParallelDials??Ni,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Or},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(uu)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new E("Not started",k.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=vi(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??Hl}),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 Bn=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 Pw=1.2,Ow=2,Uw=2e3,Fi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Bn(e.interval??5e3),this.failure=new Bn(e.interval??5e3),this.next=new Bn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Ow,this.timeoutMultiplier=e.timeoutMultiplier??Pw,this.minTimeout=e.minTimeout??Uw,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=Mr([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 $l=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 fr(this.readNext.promise,t?.signal,t)}};function Qd(){return new $l}var Vi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ql=class extends Error{code;constructor(e,t){super(e),this.code=t}},zl=class extends ql{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ki(r,e){let t=Qd();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 zl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:p}=await Promise.race([n.next(),u]);return l===!0?new we:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Vi("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 Mw=1e4,Fw="1.0.0",Vw="ping",Kw="ipfs",Jd=32,Hi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Kw}/${Vw}/${Fw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Mw,this.timeout=new Fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[kn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,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=Ki(o);t=Date.now(),await Promise.all([s.write(et(Jd),{signal:n}),s.read(Jd,{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 Hw(r){return r[Symbol.asyncIterator]!=null}function $w(...r){let e=[];for(let t of r)Hw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ai({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 vo=$w;var $i=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 E("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Mt;for await(let s of vo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",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 E(Vt.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 E(Vt.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var qi=globalThis.CustomEvent??Event;async function*Gl(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 d of r){if(s.length===t&&(i=ue(),await i.promise),f)break;let m={done:!1};s.push(m),d().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new qi("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new qi("task-complete"))})}c=!0,o.dispatchEvent(new qi("task-complete"))}catch(d){u=d,o.dispatchEvent(new qi("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*p(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*h(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let m=s[d];if(s.splice(d,1),d--,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*p():yield*h(),c&&s.length===0)break}}var zi=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 E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",k.ERR_FIND_SELF);let n=this,o=vo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Vt.NOT_FOUND,k.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Vc(1024);for await(let s of Gl(async function*(){let i=vo(...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 Gi=class extends At{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=Mr([this.shutdownController.signal,e?.signal]);ie(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await In(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=Mr([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=et(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 fr(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 Yl=32,Wl=64,Yi=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 E(`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 E(`Handler already registered for protocol ${e}`,k.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Ei.bind({ignoreUndefined:!0})({maxInboundStreams:Yl,maxOutboundStreams:Wl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new E("invalid topology",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 jl=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 ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new jl({name:e,metrics:t}):n=new Map,n}var Wi=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=ep({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ht.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new E("Transport must have a valid tag",k.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`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 E(`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 E("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 p=l.findIndex(h=>h===f);l.splice(p,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ht.NO_FATAL)throw new E(`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===Ht.FATAL_ALL)throw new E(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 Ce="/multistream/1.0.0";var ji=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Xi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function _o(r,e={}){let t=Ki(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??Le;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 ji("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Zi("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Xi("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 qw=L(`
8
- `);async function Fr(r,e,t){await r.write(e,t)}async function tp(r,e,t){await r.writeV(e,t)}async function zw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==qw[0])throw e.log.error("Invalid mss message - missing newline",t),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function hr(r,e){let t=await zw(r,e);return F(t.subarray())}async function Ao(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Gw(r,e[0],t);let n=_o(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"]',Ce,o);let s=L(`${Ce}
9
- `),i=L(`${o}
10
- `);await tp(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await hr(n,t);if(t.log.trace('select: read "%s"',a),a===Ce&&(t.log.trace("select: reading protocol response"),a=await hr(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 Fr(n,L(`${c}
11
- `),t),t.log.trace("select: reading protocol response");let u=await hr(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function Gw(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ue(),c=!1,u=!1,f=ue(),l=!1,p=!1,h=ue(),d=_o({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async y=>{let{sink:b}=d.unwrap();await b(async function*(){let x=!1;for await(let A of y){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ce,e,A.byteLength);let R=`${e}
12
- `;yield new we(Uint8Array.from([19]),L(`${Ce}
13
- `),Le(R.length),L(R),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ce,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(_=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,_)})}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 w()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await g())}finally{i=!1,s=!0,a.resolve()}}async function w(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Ce,e),await d.writeV([L(`${Ce}
14
- `),L(`${e}
15
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ce,e)}finally{c=!0,u=!1,f.resolve()}}async function g(){if(p){await h.promise;return}p=!0;try{t.log.trace("optimistic: reading multistream select header");let y=await hr(d,t);if(t.log.trace('optimistic: read multistream select header "%s"',y),y===Ce&&(y=await hr(d,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',y,e),y!==e)throw new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{l=!0,p=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*d.unwrap().source}(),r.closeRead!=null){let y=r.closeRead.bind(r);r.closeRead=async b=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await y(b)}}if(r.closeWrite!=null){let y=r.closeWrite.bind(r);r.closeWrite=async b=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await y(b)}}if(r.close!=null){let y=r.close.bind(r);r.close=async b=>{let x=[];u&&x.push(f.promise),p&&x.push(h.promise),x.length>0?await fr(Promise.all(x),b?.signal):(s=!0,i=!1,a.resolve()),await y(b)}}return{stream:r,protocol:e}}function Qi(r){return r[Symbol.asyncIterator]!=null}var Ji=r=>{let e=de(r),t=ke(e);return Le(r,t),Ji.bytes=e,t};Ji.bytes=0;function ea(r,e){e=e??{};let t=e.lengthEncoder??Ji;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Qi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}ea.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ji;return new we(t(r.byteLength),r)};var ta=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ra=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},na=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},So=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Yw=8,Ww=1024*1024*4,Vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vr||(Vr={}));var Ql=r=>{let e=lt(r);return Ql.bytes=de(e),e};Ql.bytes=0;function Zl(r,e){let t=new we,n=Vr.LENGTH,o=-1,s=e?.lengthDecoder??Ql,i=e?.maxLengthLength??Yw,a=e?.maxDataLength??Ww;function*c(){for(;t.byteLength>0;){if(n===Vr.LENGTH)try{if(o=s(t),o<0)throw new ta("Invalid message length");if(o>a)throw new ra("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Vr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new na("Message length length too long");break}throw u}if(n===Vr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Vr.LENGTH}}}return Qi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new So("Unexpected end of input")}()}Zl.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 Zl(n,{...e??{},onLength:s=>{t=s}})};async function Ro(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=_o(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await hr(n,t);if(t.log.trace('handle: read "%s"',o),o===Ce){t.log.trace('handle: respond with "%s" for "%s"',Ce,o),await Fr(n,L(`${Ce}
16
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Ce,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Fr(n,L(`${o}
17
- `),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=>ea.single(L(`${i}
18
- `))),L(`
19
- `));t.log.trace('handle: respond with "%s" for %s',e,o),await Fr(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 Fr(n,L(`na
20
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var Xw=500,Jl=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";[lu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new E("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new E("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Xw);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 np(r){return new Jl(r)}var Zw=3e4;function Qw(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 Yl}function Jw(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??Wl}function op(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var oa=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 E(`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 E("connection denied",k.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",No))};u.addEventListener("abort",f,{once:!0}),ie(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("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 p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),l=await p.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 p={...l,...o};await this.shouldBlockConnection(s,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new E("inbound connection that skipped encryption must have a peer id",k.ERR_INVALID_MULTIADDR);let h=ye(p);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 p=await this._multiplexInbound({...l,...o},this.muxers);a=p.muxerFactory,i=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=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 E("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:d=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:w,protocol:g}=await Ro(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let y=Qw(g,this.components.registrar);if(op(g,"inbound",l)===y){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,k.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=w.source,d.sink=w.sink,d.protocol=g,w.closeWrite!=null&&(d.closeWrite=w.closeWrite),w.closeRead!=null&&(d.closeRead=w.closeRead),w.close!=null&&(d.close=w.close),await this.components.peerStore.merge(i,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(async m=>{l.log.error("error handling incoming stream id %s",d.id,m.message,m.code,m.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,m={})=>{if(u==null)throw new E("Stream is not multiplexed",k.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let w=await u.newStream();l.log.trace("started new stream %s for protocols %s",w.id,d);try{if(m.signal==null){w.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let A=AbortSignal.timeout(Zw);ie(1/0,A),m={...m,signal:A}}w.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:y}=await Ao(w,d,{...m,log:w.log,yieldBytes:!0});w.log("selected protocol %s",y);let b=Jw(y,this.components.registrar,m),x=op(y,"outbound",l);if(x>=b){let A=new E(`Too many outbound protocol streams for protocol "${y}" - ${x}/${b}`,k.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw w.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[y]}),w.source=g.source,w.sink=g.sink,w.protocol=y,g.closeWrite!=null&&(w.closeWrite=g.closeWrite),g.closeRead!=null&&(w.closeRead=g.closeRead),g.close!=null&&(w.close=g.close),this.components.metrics?.trackProtocolStream(w,l),w}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),w.timeline.close==null&&w.abort(g),g.code!=null?g:new E(String(g),k.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let p=o.timeline;o.timeline=new Proxy(p,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&p.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(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(...d))}),o.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",k.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Ro(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 E(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 Ao(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 E(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 Ao(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new E(String(o),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 Ro(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),k.ERR_MUXER_UNAVAILABLE)}}};var sp="1.9.3",ip="libp2p";var eu=class extends At{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new At,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new la(a.type,{detail:a.detail}));return c||u},ie(1/0,t),this.peerId=e.peerId,this.logger=e.logger??$s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=wd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:ip,version:sp},logger:this.logger,events:t,datastore:e.datastore??new ai,connectionGater:vd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new si(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 oa(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 Wi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Mi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Hi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Yi(this.components)),this.configureComponent("addressManager",new ci(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 zi(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 $i(this.components,{routers:i})),this.configureComponent("randomWalk",new Gi(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[ia]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ia])),u[ca]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ca])),u[aa]!=null&&(this.log("registering service %s for peer discovery",a),u[aa].addEventListener?.("peer",f=>{this.#e(f)}))}bd(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 Mt;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new E("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("no protocols were provided to open a stream",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={}){ar(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=Re([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return no(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 ap(r={}){let e=r.peerId??=await Ph();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await oo(e.privateKey),new eu(await Gd(r))}async function tb(r={}){let e=await ap(r);return r.start!==!1&&await e.start(),e}return Ep(rb);})();
4
+ `));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
5
+ ${t.join(`
6
+ `)}`:`${e} :`}};Gf=Ye;C.Constructed=Gf;Ye.NAME="CONSTRUCTED";var ys=class extends Lt{fromBER(t,e,n){return e}toBER(t){return ae}};ys.override="EndOfContentValueBlock";var Wf,ws=class extends At{constructor(t={}){super(t,ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Wf=ws;C.EndOfContent=Wf;ws.NAME=Kn;var jf,Yr=class extends At{constructor(t={}){super(t,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};jf=Yr;C.Null=jf;Yr.NAME="NULL";var bs=class extends Re(Lt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=q.BufferSourceConverter.toUint8Array(t);return Pe(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,zc.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};bs.NAME="BooleanValueBlock";var Zf,xs=class extends At{constructor(t={}){super(t,bs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Zf=xs;C.Boolean=Zf;xs.NAME="BOOLEAN";var vs=class extends Re(de){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=de.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Kn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==$f)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?de.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};vs.NAME="OctetStringValueBlock";var Xf,Es=class r extends At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},vs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=Xs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Ye.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return q.BufferSourceConverter.concat(t)}};Xf=Es;C.OctetString=Xf;Es.NAME=$f;var As=class extends Re(de){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=de.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Kn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Kf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Xs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return de.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ae;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};As.NAME="BitStringValueBlock";var Yf,Jr=class extends At{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},As),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ye.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Yf=Jr;C.BitString=Yf;Jr.NAME=Kf;var Jf;function k0(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+e[0];break;default:u=s[i-l]+e[0]}switch(e[0]=u/10,!0){case l>=s.length:s=us(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return e[0]>0&&(s=us(e,s)),s}function Hf(r){if(r>=Hn.length)for(let t=Hn.length;t<=r;t++){let e=new Uint8Array([0]),n=Hn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=us(e,n)),Hn.push(n)}return Hn[r]}function C0(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-e,!0){case u<0:e=1,s[i-f]=u+10;break;default:e=0,s[i-f]=u}if(e>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-e,u<0)e=1,s[i-f]=u+10;else{e=0,s[i-f]=u;break}return s.slice()}var qn=class extends Re(Lt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=zc.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Of(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case t:e=C0(Hf(n),e),i="-";break;default:e=k0(e,Hf(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Vf.charAt(e[c]));return a===!1&&(i+=Vf.charAt(0)),i}};Jf=qn;qn.NAME="IntegerValueBlock";Object.defineProperty(Jf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Qf,St=class r extends At{constructor(t={}){super(t,qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return fs(),BigInt(this.valueBlock.toString())}static fromBigInt(t){fs();let e=BigInt(t),n=new $n,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+e,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Qf=St;C.Integer=Qf;St.NAME="INTEGER";var th,Ss=class extends St{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};th=Ss;C.Enumerated=th;Ss.NAME="ENUMERATED";var zn=class extends Re(Lt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){fs();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Xe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ae;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};zn.NAME="sidBlock";var _s=class extends Lt{constructor({value:t=tn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new zn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ae;e.push(o)}return Gc(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new zn;if(o>Number.MAX_SAFE_INTEGER){fs();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};_s.NAME="ObjectIdentifierValueBlock";var eh,Qr=class extends At{constructor(t={}){super(t,_s),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};eh=Qr;C.ObjectIdentifier=eh;Qr.NAME="OBJECT IDENTIFIER";var Gn=class extends Re(Te){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=q.BufferSourceConverter.toUint8Array(t);if(!Pe(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Xe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ae;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=q.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Gn.NAME="relativeSidBlock";var Bs=class extends Lt{constructor({value:t=tn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Gn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ae;n.push(s)}return Gc(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new Gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Bs.NAME="RelativeObjectIdentifierValueBlock";var rh,Is=class extends At{constructor(t={}){super(t,Bs),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};rh=Is;C.RelativeObjectIdentifier=rh;Is.NAME="RelativeObjectIdentifier";var nh,Le=class extends Ye{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};nh=Le;C.Sequence=nh;Le.NAME="SEQUENCE";var oh,ks=class extends Ye{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};oh=ks;C.Set=oh;ks.NAME="SET";var Cs=class extends Re(Lt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=tn}toJSON(){return{...super.toJSON(),value:this.value}}};Cs.NAME="StringValueBlock";var Ts=class extends Cs{};Ts.NAME="SimpleStringValueBlock";var Ot=class extends ps{constructor({...t}={}){super(t,Ts)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ot.NAME="SIMPLE STRING";var Ls=class extends Ot{fromBuffer(t){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=q.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ls.NAME="Utf8StringValueBlock";var sh,Ne=class extends Ls{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};sh=Ne;C.Utf8String=sh;Ne.NAME="UTF8String";var Ns=class extends Ot{fromBuffer(t){this.valueBlock.value=q.Convert.ToUtf16String(t),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(t))}};Ns.NAME="BmpStringValueBlock";var ih,Ps=class extends Ns{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};ih=Ps;C.BmpString=ih;Ps.NAME="BMPString";var Rs=class extends Ot{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Xe(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};Rs.NAME="UniversalStringValueBlock";var ah,Ds=class extends Rs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ah=Ds;C.UniversalString=ah;Ds.NAME="UniversalString";var ch,Ms=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ch=Ms;C.NumericString=ch;Ms.NAME="NumericString";var lh,Us=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};lh=Us;C.PrintableString=lh;Us.NAME="PrintableString";var uh,Os=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};uh=Os;C.TeletexString=uh;Os.NAME="TeletexString";var fh,Fs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};fh=Fs;C.VideotexString=fh;Fs.NAME="VideotexString";var hh,Vs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};hh=Vs;C.IA5String=hh;Vs.NAME="IA5String";var dh,Hs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};dh=Hs;C.GraphicString=dh;Hs.NAME="GraphicString";var ph,Wn=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ph=Wn;C.VisibleString=ph;Wn.NAME="VisibleString";var mh,$s=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};mh=$s;C.GeneralString=mh;$s.NAME="GeneralString";var gh,Ks=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};gh=Ks;C.CharacterString=gh;Ks.NAME="CharacterString";var yh,jn=class extends Wn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=qt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=qt(this.month,2),e[2]=qt(this.day,2),e[3]=qt(this.hour,2),e[4]=qt(this.minute,2),e[5]=qt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};yh=jn;C.UTCTime=yh;jn.NAME="UTCTime";var wh,qs=class extends jn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let l=new Number(t[t.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(qt(this.year,4)),e.push(qt(this.month,2)),e.push(qt(this.day,2)),e.push(qt(this.hour,2)),e.push(qt(this.minute,2)),e.push(qt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(qt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};wh=qs;C.GeneralizedTime=wh;qs.NAME="GeneralizedTime";var bh,zs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};bh=zs;C.DATE=bh;zs.NAME="DATE";var xh,Gs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};xh=Gs;C.TimeOfDay=xh;Gs.NAME="TimeOfDay";var vh,Ws=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vh=Ws;C.DateTime=vh;Ws.NAME="DateTime";var Eh,js=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Eh=js;C.Duration=Eh;js.NAME="Duration";var Ah,Zs=class extends Ne{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ah=Zs;C.TIME=Ah;Zs.NAME="TIME";function H(r,t="utf8"){let e=ss[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function en(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return qr(r)}var Zn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Xn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Ys=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Sh={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Ys("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Je=Sh;async function _h(r){let t=await Je.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await L0(t);return{privateKey:e[0],publicKey:e[1]}}async function Bh(r,t){let e=await Je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Je.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ih(r,t,e){let n=await Je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Je.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function L0(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([Je.get().subtle.exportKey("jwk",r.privateKey),Je.get().subtle.exportKey("jwk",r.publicKey)])}function Zc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var rn=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pt.createV1(114,this._multihash)}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return Ih(this._key,e,t)}},Jn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return Bh(this._key,t)}};var Js=8192,Xc=18;function kh(r){let{result:t}=jc(r),e=t.valueBlock.value;return{n:H(pe(e[1].toBigInt()),"base64url"),e:H(pe(e[2].toBigInt()),"base64url"),d:H(pe(e[3].toBigInt()),"base64url"),p:H(pe(e[4].toBigInt()),"base64url"),q:H(pe(e[5].toBigInt()),"base64url"),dp:H(pe(e[6].toBigInt()),"base64url"),dq:H(pe(e[7].toBigInt()),"base64url"),qi:H(pe(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function N0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new D("JWK was missing components");let e=new Le({value:[new St({value:0}),St.fromBigInt(me(P(r.n,"base64url"))),St.fromBigInt(me(P(r.e,"base64url"))),St.fromBigInt(me(P(r.d,"base64url"))),St.fromBigInt(me(P(r.p,"base64url"))),St.fromBigInt(me(P(r.q,"base64url"))),St.fromBigInt(me(P(r.dp,"base64url"))),St.fromBigInt(me(P(r.dq,"base64url"))),St.fromBigInt(me(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Ch(r){let{result:t}=jc(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(pe(e[0].toBigInt()),"base64url"),e:H(pe(e[1].toBigInt()),"base64url")}}function Yc(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let e=new Le({value:[new Le({value:[new Qr({value:"1.2.840.113549.1.1.1"}),new Yr]}),new Jr({valueHex:new Le({value:[St.fromBigInt(me(P(r.n,"base64url"))),St.fromBigInt(me(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function pe(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,s=0;for(;o<e;)n[o]=parseInt(t.slice(s,s+2),16),o+=1,s+=2;return n}function me(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Th(r){let t=kh(r);return Lh(t)}function Jc(r){let t=Ch(r);if(Zc(t)>Js)throw new Nr("Key size is too large");let e=Zr(he.encode({Type:gt.RSA,Data:r})),n=te(Xc,e);return new rn(t,n)}function Lh(r){if(Zc(r)>Js)throw new D("Key size is too large");let t=Nh(r),e=Zr(he.encode({Type:gt.RSA,Data:Yc(t.publicKey)})),n=te(Xc,e);return new Jn(t.privateKey,new rn(t.publicKey,n))}async function Qc(r){if(r>Js)throw new D("Key size is too large");let t=await _h(r),e=Zr(he.encode({Type:gt.RSA,Data:Yc(t.publicKey)})),n=te(Xc,e);return new Jn(t.privateKey,new rn(t.publicKey,n))}function Nh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Qs=class extends Kr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qu(t);let n=Ln(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return $r(this),this.iHash.update(t),this}digestInto(t){$r(this),Hr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tl=(r,t,e)=>new Qs(r,t).update(e).digest();tl.create=(r,t)=>new Qs(r,t);function Ph(r){r.lowS!==void 0&&ne("lowS",r.lowS),r.prehash!==void 0&&ne("prehash",r.prehash)}function P0(r){let t=Rn(r);ue(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:R0,hexToBytes:D0}=Zo,De={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=De;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=ar(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?ar(o.length/2|128):"";return`${ar(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=De,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=De;if(r<Me)throw new t("integer: negative integers are not allowed");let e=ar(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=De;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return R0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=De,o=typeof r=="string"?D0(r):r;Gr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=De,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Me=BigInt(0),vt=BigInt(1),Qv=BigInt(2),Rh=BigInt(3),t2=BigInt(4);function M0(r){let t=P0(r),{Fp:e}=t,n=Ge(t.n,t.nBitLength),o=t.toBytes||((m,g,y)=>{let b=g.toAffine();return ke(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let g=m.subarray(1),y=e.fromBytes(g.subarray(0,e.BYTES)),b=e.fromBytes(g.subarray(e.BYTES,2*e.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=t,b=e.sqr(m),w=e.mul(b,m);return e.add(e.add(w,e.mul(m,g)),y)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Nn(m,vt,t.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=t;if(g&&typeof m!="bigint"){if(Ke(m)&&(m=Be(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:Ie(at("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=Y(x,w)),$t("private key",x,vt,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=ur((m,g)=>{let{px:y,py:b,pz:w}=m;if(e.eql(w,e.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?e.ONE:e.inv(w));let A=e.mul(y,g),_=e.mul(b,g),v=e.mul(w,g);if(x)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=ur(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!e.isValid(g)||!e.isValid(y))throw new Error("bad point: x or y not FE");let b=e.sqr(y),w=i(g);if(!e.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!e.isValid(g))throw new Error("x required");if(y==null||!e.isValid(y))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!e.isValid(y)||!e.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>e.eql(x,e.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=e.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(at("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Jo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(e.isOdd)return!e.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=e.eql(e.mul(y,_),e.mul(x,w)),B=e.eql(e.mul(b,_),e.mul(A,w));return v&&B}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:g,b:y}=t,b=e.mul(y,Rh),{px:w,py:x,pz:A}=this,_=e.ZERO,v=e.ZERO,B=e.ZERO,T=e.mul(w,w),et=e.mul(x,x),V=e.mul(A,A),F=e.mul(w,x);return F=e.add(F,F),B=e.mul(w,A),B=e.add(B,B),_=e.mul(g,B),v=e.mul(b,V),v=e.add(_,v),_=e.sub(et,v),v=e.add(et,v),v=e.mul(_,v),_=e.mul(F,_),B=e.mul(b,B),V=e.mul(g,V),F=e.sub(T,V),F=e.mul(g,F),F=e.add(F,B),B=e.add(T,T),T=e.add(B,T),T=e.add(T,V),T=e.mul(T,F),v=e.add(v,T),V=e.mul(x,A),V=e.add(V,V),T=e.mul(V,F),_=e.sub(_,T),B=e.mul(V,et),B=e.add(B,B),B=e.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=e.ZERO,B=e.ZERO,T=e.ZERO,et=t.a,V=e.mul(t.b,Rh),F=e.mul(y,x),R=e.mul(b,A),k=e.mul(w,_),L=e.add(y,b),S=e.add(x,A);L=e.mul(L,S),S=e.add(F,R),L=e.sub(L,S),S=e.add(y,w);let E=e.add(x,_);return S=e.mul(S,E),E=e.add(F,k),S=e.sub(S,E),E=e.add(b,w),v=e.add(A,_),E=e.mul(E,v),v=e.add(R,k),E=e.sub(E,v),T=e.mul(et,S),v=e.mul(V,k),T=e.add(v,T),v=e.sub(R,T),T=e.add(R,T),B=e.mul(v,T),R=e.add(F,F),R=e.add(R,F),k=e.mul(et,k),S=e.mul(V,S),R=e.add(R,k),k=e.sub(F,k),k=e.mul(et,k),S=e.add(S,k),F=e.mul(R,S),B=e.add(B,F),F=e.mul(E,S),v=e.mul(L,v),v=e.sub(v,F),F=e.mul(L,R),T=e.mul(E,T),T=e.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$t("scalar",g,Me,t.n);let y=d.ZERO;if(g===Me)return y;if(g===vt)return this;let{endo:b}=t;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Me||_>Me;)x&vt&&(v=v.add(T)),_&vt&&(B=B.add(T)),T=T.double(),x>>=vt,_>>=vt;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(e.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=t;$t("scalar",g,vt,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:et}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(e.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=et.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Me||v===vt||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=t;if(g===vt)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=t;return g===vt?this:y?y(d,this):this.multiplyUnsafe(t.h)}toRawBytes(g=!0){return ne("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return ne("isCompressed",g),Be(this.toRawBytes(g))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,p=Yo(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function U0(r){let t=Rn(r);return ue(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Dh(r){let t=U0(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(k){return Y(k,n)}function a(k){return Xo(k,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=M0({...t,toBytes(k,L,S){let E=L.toAffine(),I=e.toBytes(E.x),N=ke;return ne("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),I):N(Uint8Array.from([4]),I,e.toBytes(E.y))},fromBytes(k){let L=k.length,S=k[0],E=k.subarray(1);if(L===o&&(S===2||S===3)){let I=Ie(E);if(!Nn(I,vt,e.ORDER))throw new Error("Point is not on curve");let N=f(I),M;try{M=e.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&vt)===vt;return(S&1)===1!==U&&(M=e.neg(M)),{x:I,y:M}}else if(L===s&&S===4){let I=e.fromBytes(E.subarray(0,e.BYTES)),N=e.fromBytes(E.subarray(e.BYTES,2*e.BYTES));return{x:I,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=k=>Be(ze(k,t.nByteLength));function h(k){let L=n>>vt;return k>L}function p(k){return h(k)?i(-k):k}let m=(k,L,S)=>Ie(k.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=t.nByteLength;return L=at("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=De.toSig(at("DER",L));return new g(S,E)}assertValidity(){$t("r",this.r,vt,n),$t("s",this.s,vt,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:I}=this,N=_(at("msgHash",L));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let M=I===2||I===3?S+t.n:S;if(M>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=I&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),X=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,X);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return cr(this.toDERHex())}toDERHex(){return De.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return cr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(k){try{return u(k),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let k=nc(t.n);return df(t.randomBytes(k),t.n)},precompute(k=8,L=c.BASE){return L._setWindowSize(k),L.multiply(BigInt(3)),L}};function b(k,L=!0){return c.fromPrivateKey(k).toRawBytes(L)}function w(k){let L=Ke(k),S=typeof k=="string",E=(L||S)&&k.length;return L?E===o||E===s:S?E===2*o||E===2*s:k instanceof c}function x(k,L,S=!0){if(w(k))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(k)).toRawBytes(S)}let A=t.bits2int||function(k){let L=Ie(k),S=k.length*8-t.nBitLength;return S>0?L>>BigInt(S):L},_=t.bits2int_modN||function(k){return i(A(k))},v=Pn(t.nBitLength);function B(k){return $t(`num < 2^${t.nBitLength}`,k,Me,v),ze(k,t.nByteLength)}function T(k,L,S=et){if(["recovered","canonical"].some(xt=>xt in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:I}=t,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),k=at("msgHash",k),Ph(S),M&&(k=at("prehashed msgHash",E(k)));let $=_(k),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let xt=U===!0?I(e.BYTES):U;K.push(at("extraEntropy",xt))}let X=ke(...K),Q=$;function bt(xt){let Et=A(xt);if(!l(Et))return;let Pt=a(Et),dt=c.BASE.multiply(Et).toAffine(),Ht=i(dt.x);if(Ht===Me)return;let we=i(Pt*i(Q+Ht*z));if(we===Me)return;let An=(dt.x===Ht?0:2)|Number(dt.y&vt),Sn=we;return N&&h(we)&&(Sn=p(we),An^=1),new g(Ht,Sn,An)}return{seed:X,k2sig:bt}}let et={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function F(k,L,S=et){let{seed:E,k2sig:I}=T(k,L,S),N=t;return Qa(N.hash.outputLen,N.nByteLength,N.hmac)(E,I)}c.BASE._setWindowSize(8);function R(k,L,S,E=V){let I=k;if(L=at("msgHash",L),S=at("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");Ph(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof I=="string"||Ke(I))try{U=g.fromDER(I)}catch(dt){if(!(dt instanceof De.Err))throw dt;U=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:dt,s:Ht}=I;U=new g(dt,Ht)}else throw new Error("PARSE");$=c.fromHex(S)}catch(dt){if(dt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=t.hash(L));let{r:z,s:K}=U,X=_(L),Q=a(K),bt=i(X*Q),xt=i(z*Q),Et=c.BASE.multiplyAndAddUnsafe($,bt,xt)?.toAffine();return Et?i(Et.x)===z:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function O0(r){return{hash:r,hmac:(t,...e)=>tl(r,t,za(...e)),randomBytes:qr}}function Mh(r,t){let e=n=>Dh({...r,...O0(n)});return Object.freeze({...e(t),create:e})}var Fh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),F0=BigInt(1),el=BigInt(2),Oh=(r,t)=>(r+t/el)/t;function V0(r){let t=Fh,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=nt(f,e,t)*f%t,d=nt(l,e,t)*f%t,h=nt(d,el,t)*u%t,p=nt(h,o,t)*h%t,m=nt(p,s,t)*p%t,g=nt(m,a,t)*m%t,y=nt(g,c,t)*g%t,b=nt(y,a,t)*m%t,w=nt(b,e,t)*f%t,x=nt(w,i,t)*p%t,A=nt(x,n,t)*u%t,_=nt(A,el,t);if(!rl.eql(rl.sqr(_),r))throw new Error("Cannot find square root");return _}var rl=Ge(Fh,void 0,void 0,{sqrt:V0}),Xt=Mh({a:BigInt(0),b:BigInt(7),Fp:rl,n:Uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Uh,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-F0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Oh(s*r,t),c=Oh(-n*r,t),u=Y(r-a*e-c*o,t),f=Y(-a*n-c*s,t),l=u>i,d=f>i;if(l&&(u=t-u),d&&(f=t-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Zr),l2=BigInt(0);var u2=Xt.ProjectivePoint;function Ft(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=It(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function nl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Vh(r,t){let e=Wr.digest(t instanceof Uint8Array?t:t.subarray());if(nl(e))return e.then(({digest:n})=>Xt.sign(n,r).toDERRawBytes()).catch(n=>{throw new Zn(String(n))});try{return Xt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Zn(String(n))}}function Hh(r,t,e){let n=Wr.digest(e instanceof Uint8Array?e:e.subarray());if(nl(n))return n.then(({digest:o})=>Xt.verify(t,o,r)).catch(o=>{throw new Xn(String(o))});try{return Xt.verify(t,n.digest,r)}catch(o){throw new Xn(String(o))}}var Qn=class{type="secp256k1";raw;_key;constructor(t){this._key=qh(t),this.raw=$h(this._key)}toMultihash(){return Se.digest(fe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}verify(t,e){return Hh(this._key,e,t)}},ti=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Kh(t),this.publicKey=new Qn(e??zh(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:it(this.raw,t.raw)}sign(t){return Vh(this.raw,t)}};function ol(r){return new Qn(r)}async function Gh(){let r=H0();return new ti(r)}function $h(r){return Xt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Kh(r){try{return Xt.getPublicKey(r,!0),r}catch(t){throw new _n(String(t))}}function qh(r){try{return Xt.ProjectivePoint.fromHex(r),r}catch(t){throw new Nr(String(t))}}function zh(r){try{return Xt.getPublicKey(r,!0)}catch(t){throw new _n(String(t))}}function H0(){return Xt.utils.randomPrivateKey()}async function Wh(r,t){if(r==="Ed25519")return Ef();if(r==="secp256k1")return Gh();if(r==="RSA")return Qc(t??2048);throw new Fe}function nn(r){let{Type:t,Data:e}=he.decode(r),n=e??new Uint8Array;switch(t){case gt.RSA:return Jc(n);case gt.Ed25519:return cc(n);case gt.secp256k1:return ol(n);default:throw new Fe}}function jh(r){let{Type:t,Data:e}=he.decode(r.digest),n=e??new Uint8Array;switch(t){case gt.Ed25519:return cc(n);case gt.secp256k1:return ol(n);default:throw new Fe}}function fe(r){return he.encode({Type:gt[r.type],Data:r.raw})}var Zh=Symbol.for("nodejs.util.inspect.custom"),$0=114,to=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[No]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pt.createV1($0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return it(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return it(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Zh](){return`PeerId(${this.toString()})`}},eo=class extends to{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ro=class extends to{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},no=class extends to{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},K0=2336,oo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Se.digest(P(this.url))}[Zh](){return`PeerId(${this.url})`}[No]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pt.createV1(K0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};var q0=114,Xh=2336;function ge(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=ee(W.decode(`z${r}`));else{if(t==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=ee(t.decode(r))}return on(e)}function sl(r){if(r.type==="Ed25519")return new ro({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new eo({multihash:r.toCID().multihash,publicKey:r});throw new Fe}function Yh(r){return sl(r.publicKey)}function on(r){if(G0(r))return new eo({multihash:r});if(z0(r))try{let t=jh(r);if(t.type==="Ed25519")return new ro({multihash:r,publicKey:t});if(t.type==="secp256k1")return new no({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new oo(new URL(e))}throw new Fo("Supplied PeerID Multihash is invalid")}function ei(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==q0&&r.code!==Xh)throw new Oo("Supplied PeerID CID is invalid");if(r.code===Xh){let t=H(r.multihash.digest);return new oo(new URL(t))}return on(r.multihash)}function z0(r){return r.code===Se.code}function G0(r){return r.code===Wr.code}var ri=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jh=45,W0=15,sn=new ri;function il(r){if(!(r.length>W0))return sn.new(r).parseWith(()=>sn.readIPv4Addr())}function al(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return sn.new(r).parseWith(()=>sn.readIPv6Addr())}function ni(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return sn.new(r).parseWith(()=>sn.readIPAddr())}function an(r){return!!il(r)}function cn(r){return!!al(r)}function oi(r){return!!ni(r)}var bE=parseInt("0xFFFF",16),xE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ed=an,J0=cn,cl=function(r){let t=0;if(r=r.toString().trim(),ed(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(J0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=ed(e[n]),i;s&&(i=cl(e[n]),e[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},rd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ln={},ll={},ty=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];ty.forEach(r=>{let t=ey(...r);ll[t.code]=t,ln[t.name]=t});function ey(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(ll[r]!=null)return ll[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ln[r]!=null)return ln[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var eA=Z("ip4"),rA=Z("ip6"),nA=Z("ipcidr");function dl(r,t){switch(Z(r).code){case 4:case 41:return ny(t);case 42:return hl(t);case 6:case 273:case 33:case 132:return sd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hl(t);case 421:return ay(t);case 444:return od(t);case 445:return od(t);case 466:return iy(t);case 481:return globalThis.encodeURIComponent(hl(t));default:return H(t,"base16")}}function pl(r,t){switch(Z(r).code){case 4:return nd(t);case 41:return nd(t);case 42:return fl(t);case 6:case 273:case 33:case 132:return ml(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return fl(t);case 421:return oy(t);case 444:return cy(t);case 445:return ly(t);case 466:return sy(t);case 481:return fl(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}var ul=Object.values(Un).map(r=>r.decoder),ry=function(){let r=ul[0].or(ul[1]);return ul.slice(2).forEach(t=>r=r.or(t)),r}();function nd(r){if(!oi(r))throw new Error("invalid ip address");return cl(r)}function ny(r){let t=rd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!oi(t))throw new Error("invalid ip address");return t}function ml(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function sd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function fl(r){let t=P(r),e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function hl(r){let t=se(r);if(r=r.slice(ht(t)),r.length!==t)throw new Error("inconsistent lengths");return H(r)}function oy(r){let t;r[0]==="Q"||r[0]==="1"?t=ee(W.decode(`z${r}`)).bytes:t=pt.parse(r).multihash.bytes;let e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function sy(r){let t=ry.decode(r),e=Uint8Array.from(Ct(t.length));return Ft([e,t],e.length+t.length)}function iy(r){let t=se(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+H(e,"base64url")}function ay(r){let t=se(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return H(e,"base58btc")}function cy(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=zt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ml(n);return Ft([e,o],e.length+o.length)}function ly(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=zt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ml(n);return Ft([e,o],e.length+o.length)}function od(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=H(t,"base32"),o=sd(e);return`${n}:${o}`}function id(r){r=gl(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Z(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw cd("invalid address: "+r);if(a.path===!0){n=gl(o.slice(s).join("/")),t.push([a.code,pl(a.code,n)]),e.push([a.code,n]);break}let c=pl(a.code,o[s]);t.push([a.code,c]),e.push([a.code,dl(a.code,c)])}return{string:ad(e),bytes:wl(t),tuples:t,stringTuples:e,path:n}}function yl(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=se(r,o),i=ht(s),a=Z(s),c=uy(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw cd("Invalid address Uint8Array: "+H(r,"base16"));t.push([s,u]);let f=dl(s,u);if(e.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:ad(e),tuples:t,stringTuples:e,path:n}}function ad(r){let t=[];return r.map(e=>{let n=Z(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),gl(t.join("/"))}function wl(r){return Ft(r.map(t=>{let e=Z(t[0]),n=Uint8Array.from(Ct(e.code));return t.length>1&&t[1]!=null&&(n=Ft([n,t[1]])),n}))}function uy(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=se(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ht(e)}}function gl(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function cd(r){return new Error("Error parsing address: "+r)}var fy=Symbol.for("nodejs.util.inspect.custom"),xl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),hy=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],bl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},si=class r{bytes;#t;#e;#s;#a;[xl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=yl(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=id(t)}else if(Qe(t))e=yl(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#s=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),hy.includes(h)&&(e=i.name,o=443,n=`${p??""}${s}`,t=h===f.code?6:4),(h===i.code||h===a.code)&&(e=Z(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(e=Z(h).name,n=`${p??""}${s}`,t=h===u.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},Z(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Z(t).name)}tuples(){return this.#e}stringTuples(){return this.#s}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(wl(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===ln.p2p.code&&t.push([n,o]),n===ln["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return it(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=un.get(e.name);if(n==null)throw new bl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ot(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[fy](){return`Multiaddr(${this.#t})`}};var un=new Map;function Qe(r){return!!r?.[xl]}function ot(r){return new si(r)}var dy=r=>r.toString().split("/").slice(1),so=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),G=r=>({match:t=>so(e=>e===r).match(t),pattern:r}),ci=()=>({match:r=>so(t=>typeof t=="string").match(r),pattern:"{string}"}),li=()=>({match:r=>so(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),_t=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ii=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Bc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),yt=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Yt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),J=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function ut(...r){function t(o){let s=dy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var El=J(G("dns4"),ci()),Al=J(G("dns6"),ci()),Sl=J(G("dnsaddr"),ci()),ld=J(G("dns"),ci()),LA=ut(El),NA=ut(Al),PA=ut(Sl),RA=ut(Yt(ld,Sl,El,Al)),ud=J(G("ip4"),so(an)),fd=J(G("ip6"),so(cn)),hd=Yt(ud,fd),ye=Yt(hd,ld,El,Al,Sl),DA=ut(ye),MA=ut(ud),UA=ut(fd),OA=ut(hd),_l=J(ye,G("tcp"),li()),io=J(ye,G("udp"),li()),FA=ut(_l),VA=ut(io),Bl=J(io,G("quic")),ui=J(io,G("quic-v1")),py=Yt(Bl,ui),HA=ut(Bl),$A=ut(ui),vl=Yt(ye,_l,io,Bl,ui),dd=Yt(J(vl,G("ws"),yt(_t()))),KA=ut(dd),pd=Yt(J(vl,G("wss"),yt(_t())),J(vl,G("tls"),G("ws"),yt(_t()))),qA=ut(pd),md=J(io,G("webrtc-direct"),yt(ii()),yt(ii()),yt(_t())),zA=ut(md),gd=J(ui,G("webtransport"),yt(ii()),yt(ii()),yt(_t())),GA=ut(gd),ai=Yt(dd,pd,J(_l,yt(_t())),J(py,yt(_t())),J(ye,yt(_t())),md,gd,_t()),WA=ut(ai),my=J(ai,G("p2p-circuit"),_t()),ao=ut(my),gy=Yt(J(ai,G("p2p-circuit"),G("webrtc"),yt(_t())),J(ai,G("webrtc"),yt(_t())),G("webrtc")),jA=ut(gy),yy=Yt(J(ye,G("tcp"),li(),G("http"),yt(_t())),J(ye,G("http"),yt(_t()))),ZA=ut(yy),wy=Yt(J(ye,G("tcp"),Yt(J(G("443"),G("http")),J(li(),G("https"))),yt(_t())),J(ye,G("tls"),G("http"),yt(_t())),J(ye,G("https"),yt(_t()))),XA=ut(wy);var wd=sr(yd(),1),by=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],xy=by.map(r=>new wd.Netmask(r));function Il(r){for(let t of xy)if(t.contains(r))return!0;return!1}function vy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ey(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Il(o)}function Ay(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Sy(r){let t=r.split(":"),e=t[t.length-1];return Il(e)}function _y(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function fi(r){return an(r)?Il(r):vy(r)?Ey(r):Ay(r)?Sy(r):cn(r)?_y(r):void 0}function kl(r){try{let{address:t}=r.nodeAddress();return!!fi(t)}catch{return!0}}function By(r,t){let e=kl(r.multiaddr),n=kl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Iy(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ky(r,t){let e=ao.exactMatch(r.multiaddr),n=ao.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function fn(r,t){let e=By(r,t);if(e!==0)return e;let n=ky(r,t);return n!==0?n:Iy(r,t)}var ft=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Tl=sr(xd(),1);var uo=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Ll=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},vd=r=>globalThis.DOMException===void 0?new Ll(r):new DOMException(r),Ed=r=>{let t=r.reason===void 0?vd("This operation was aborted."):r.reason;return t instanceof Error?t:vd(t)};function fo(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Ed(d)),d.addEventListener("abort",()=>{f(Ed(d))})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new uo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${e} milliseconds`,f(l))},e),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Nl(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var ho=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Nl(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var tr=class extends Tl.default{#t;#e;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ho,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#b(){return this.#e||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#n===void 0){let e=this.#p-t;if(e<0)this.#s=this.#t?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},e)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#A;if(this.#b&&this.#x){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#t?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#h()}async#S(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=fo(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#S(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof uo&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#o}get isPaused(){return this.#i}};function di(r){let t=[Wt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Pl=60;function pi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:Wt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Wt[t.type],TTL:t.TTL??t.ttl??Pl,data:t.data instanceof Uint8Array?H(t.data):t.data}))}}var Ly=4;function Rl(r,t={}){let e=new tr({concurrency:t.queryConcurrency??Ly});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),di(o.types).forEach(a=>{s.append("type",Wt[a])}),o.onProgress?.(new ft("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=pi(await a.json());return o.onProgress?.(new ft("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ad(){return[Rl("https://cloudflare-dns.com/dns-query"),Rl("https://dns.google/resolve")]}var Bd=sr(_d(),1);var Dl=class{lru;constructor(t){this.lru=(0,Bd.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return pi({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Wt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Pl)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Id(r){return new Dl(r)}var Ny=1e3,mi=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Id(t.cacheSize??Ny),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ad())}async query(t,e={}){let n=di(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new ft("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let f of u.Answer)this.cache.add(t,f);return u}catch(u){a.push(u),e.onProgress?.(new ft("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Wt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Wt||(Wt={}));function kd(r={}){return new mi(r)}var Py=32,{code:Ry}=Z("dnsaddr"),Ml=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},yr=async function(t,e={}){let n=e.maxRecursiveDepth??Py;if(n===0)throw new Ml("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===Ry)??[],i=await(e?.dns??kd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Wt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ot(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Ud=sr(Md(),1),wi=Ud.default;var Vy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:yr},addressSorter:fn},transportManager:{faultTolerance:Oe.FATAL_ALL}};async function Od(r){let t=wi(Vy,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return t}function Hy(r,t){try{if(typeof r=="string"&&r.length>0)return $y(r);if(typeof r=="number"&&isFinite(r))return t?.long?qy(r):Ky(r);throw new Error("Value is not a string or number.")}catch(e){let n=zy(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function $y(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var xi=Hy;function Ky(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function qy(r){let t=Math.abs(r);return t>=864e5?bi(r,t,864e5,"day"):t>=36e5?bi(r,t,36e5,"hour"):t>=6e4?bi(r,t,6e4,"minute"):t>=1e3?bi(r,t,1e3,"second"):`${r} ms`}function bi(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function zy(r){return typeof r=="object"&&r!==null&&"message"in r}function Ol(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=xi,e.destroy=u,Object.keys(r).forEach(f=>{e[f]=r[f]}),e.names=[],e.skips=[],e.formatters={};function t(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return e.colors[Math.abs(l)%e.colors.length]}e.selectColor=t;function e(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=e.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),e.formatArgs.call(y,g),(y.log||e.log).apply(y,g)}return m.namespace=f,m.useColors=e.useColors(),m.color=e.selectColor(f),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(f)),p),set:g=>{d=g}}),typeof e.init=="function"&&e.init(m),m}function n(f,l){let d=e(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){e.save(f),e.namespaces=f,e.names=[],e.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?e.skips.push(new RegExp("^"+f.substr(1)+"$")):e.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...e.names.map(a),...e.skips.map(a).map(l=>"-"+l)].join(",");return e.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=e.skips.length;l<d;l++)if(e.skips[l].test(f))return!1;for(l=0,d=e.names.length;l<d;l++)if(e.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var vi=Jy(),Gy=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Wy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function jy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+xi(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var Zy=console.debug??console.log??(()=>{});function Xy(r){try{r?vi?.setItem("debug",r):vi?.removeItem("debug")}catch{}}function Yy(){let r;try{r=vi?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Jy(){try{return localStorage}catch{}}function Qy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Fd=Ol({formatArgs:jy,save:Xy,load:Yy,useColors:Wy,setupFormatters:Qy,colors:Gy,storage:vi,log:Zy});var jt=Fd;jt.formatters.b=r=>r==null?"undefined":W.baseEncode(r);jt.formatters.t=r=>r==null?"undefined":zt.baseEncode(r);jt.formatters.m=r=>r==null?"undefined":_c.baseEncode(r);jt.formatters.p=r=>r==null?"undefined":r.toString();jt.formatters.c=r=>r==null?"undefined":r.toString();jt.formatters.k=r=>r==null?"undefined":r.toString();jt.formatters.a=r=>r==null?"undefined":r.toString();function tw(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ei(){return{forComponent(r){return ew(r)}}}function ew(r){let t=tw(`${r}:trace`);return jt.enabled(`${r}:trace`)&&jt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=jt(`${r}:trace`)),Object.assign(jt(r),{error:jt(`${r}:error`),trace:t})}function wr(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function Ai(r){let t=ee(W.decode(`z${r}`));return on(t)}var ce=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return wr(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return wr(this.map.values(),t=>t.key)}values(){return wr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var br=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return wr(this.set.entries(),t=>{let e=Ai(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Ai(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return wr(this.set.values(),t=>Ai(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var qd=Symbol.for("@achingbrain/uint8arraylist");function Kd(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function _i(r){return!!r?.[qd]}var wt=class r{bufs;length;[qd]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(_i(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(_i(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Kd(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Kd(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(_i(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Ft(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ft(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_i(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=It(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=It(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!it(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Fl=64,le=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Fl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ct(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?it(this.fp,t.fp):!1}};function xr(r,t){return Math.floor(Math.random()*(t-r))+r}var vr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=xr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Vl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},zd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gd=new globalThis.TextEncoder;function rw(r,t){let e=Vl[t],n=zd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function nw(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Vl[t],o=zd[t],s=r;for(;s.length>0;){let i=Gd.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Hl(r,{size:t=32,utf8Buffer:e}={}){if(!Vl[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return nw(r,t,e);r=Gd.encode(r)}return rw(r,t)}var ow=sr($d(),1);var mo={hash:r=>Number(Hl(r,{size:32})),hashV:(r,t)=>sw(mo.hash(r,t))};function sw(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var iw=500,go=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??mo,this.seed=t.seed??xr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new vr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))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<iw;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new vr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},aw={1:.5,2:.84,4:.95,8:.98};function cw(r=.001){return r>.002?2:r>1e-5?4:8}function Wd(r,t=.001){let e=cw(t),n=aw[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Fl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Bi=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??mo,this.seed=t.seed??xr(0,Math.pow(2,10)),this.filterSeries=[new go({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=P(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new go({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function $l(r,t=.001,e){return new Bi({...Wd(r,t),...e??{}})}var yo;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(yo||(yo={}));var Ii=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var pn=class r{static createFromProtobuf=async t=>{let e=yo.decode(t),n=nn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=jd(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Ii("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=yo.encode({publicKey:fe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return it(this.marshal(),t.marshal())}async validate(t){let e=jd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},jd=(r,t,e)=>{let n=P(r),o=Ct(n.byteLength),s=Ct(t.length),i=Ct(e.length);return new wt(o,n,s,t,i,e)};function Zd(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var Xd="libp2p-peer-record",Yd=Uint8Array.from([3,1]);var wo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Ut((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ct(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Mt(s,n.codec()),n.decode=(s,i)=>Dt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Ut((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ct(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new 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})),e),r.encode=n=>Mt(n,r.codec()),r.decode=(n,o)=>Dt(n,r.codec(),o)})(wo||(wo={}));var Er=class r{static createFromProtobuf=t=>{let e=wo.decode(t),n=on(ee(e.peerId)),o=(e.addresses??[]).map(i=>ot(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xd;static CODEC=Yd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=wo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!Zd(this.multiaddrs,t.multiaddrs))}};function lw(r){return r[Symbol.asyncIterator]!=null}function uw(r){if(lw(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var bo=uw;var er={},mn=r=>{r.addEventListener("message",t=>{mn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{mn.dispatchEvent("message",r,t)})};mn.addEventListener=(r,t)=>{er[r]==null&&(er[r]=[]),er[r].push(t)};mn.removeEventListener=(r,t)=>{er[r]!=null&&(er[r]=er[r].filter(e=>e===t))};mn.dispatchEvent=function(r,t,e){er[r]!=null&&er[r].forEach(n=>n(t,e))};var Kl=mn;var ql="lock:worker:request-read",zl="lock:worker:release-read",Gl="lock:master:grant-read",Wl="lock:worker:request-write",jl="lock:worker:release-write",Zl="lock:master:grant-write";var Jd=(r=21)=>Math.random().toString().substring(2);var Qd=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},tp=(r,t,e,n)=>async()=>{let o=Jd();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},fw={singleProcess:!1},ep=r=>{if(r=Object.assign({},fw,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return Kl.addEventListener("message",Qd(e,"requestReadLock",ql,zl,Gl)),Kl.addEventListener("message",Qd(e,"requestWriteLock",Wl,jl,Zl)),e}return{isWorker:!0,readLock:e=>tp(e,ql,Gl,zl),writeLock:e=>tp(e,Wl,Zl,jl)}};var Ar={},rr;async function Xl(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>fo((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var hw=(r,t)=>{if(rr.isWorker===!0)return{readLock:rr.readLock(r,t),writeLock:rr.writeLock(r,t)};let e=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return Xl(n,t);n=new tr({concurrency:t.concurrency,autoStart:!1});let o=n,s=Xl(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Xl(e,t)}}},dw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Yl(r){let t=Object.assign({},dw,r);return rr==null&&(rr=ep(t),rr.isWorker!==!0&&(rr.addEventListener("requestReadLock",e=>{Ar[e.data.name]!=null&&Ar[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),rr.addEventListener("requestWriteLock",async e=>{Ar[e.data.name]!=null&&Ar[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Ar[t.name]==null&&(Ar[t.name]=hw(t.name,t)),Ar[t.name]}var gn;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ut((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:"",value:ct(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ut((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ci.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=Ci.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ut((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ki.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(ki.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 Vn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Vn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Mt(o,r.codec()),r.decode=(o,s)=>Dt(o,r.codec(),s)})(gn||(gn={}));var ki;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ki||(ki={}));var Ci;(function(r){let t;r.codec=()=>(t==null&&(t=Ut((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Ci||(Ci={}));function yn(r,t){let e=gn.decode(t);if(e.publicKey!=null&&r.publicKey==null){let s=nn(e.publicKey);r=sl(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:r,addresses:e.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ot(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}var Ue="/",rp=new TextEncoder().encode(Ue),Ti=rp[0],Sr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ti)throw new Error("Invalid key")}toString(t="utf8"){return H(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ue))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=rp),this._buf[0]!==Ti){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ti,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ti;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Ue).slice(1)}type(){return pw(this.baseNamespace())}name(){return mw(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ue)||(t+=Ue),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ue):new r(t.slice(0,-1).join(Ue))}child(t){return this.toString()===Ue?t:t.toString()===Ue?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...gw(t.map(e=>e.namespaces()))])}};function pw(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function mw(r){let t=r.split(":");return t[t.length-1]}function gw(r){return[].concat(...r)}var Jl="/peers/";function wn(r){if(!Po(r)||r.type==null)throw new D("Invalid PeerId");let t=r.toCID().toString();return new Sr(`${Jl}${t}`)}async function np(r,t,e){let n=new Map;for(let o of e){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ot(o.multiaddr)),!Qe(o.multiaddr))throw new D("Multiaddr was invalid");if(!await t(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Ni(r,t,e,n){if(t==null)throw new D("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Li(d,{validate:op})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Li(d,{validate:sp,map:ip})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Li([...a.entries()],{validate:op})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Li([...h.entries()],{validate:sp,map:ip})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=fe(o.id.publicKey):t.publicKey!=null?f=fe(t.publicKey):r.publicKey!=null&&(f=fe(r.publicKey));let l={addresses:await np(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Li(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function op(r,t){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function sp(r,t){if(typeof r!="string")throw new D("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new D("Tag value must be an integer");if(t.value<0||t.value>100)throw new D("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new D("Tag ttl must be an integer");if(t.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function ip(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Pi(r,t,e){let n=r.toString().split("/")[2],o=pt.parse(n,zt),s=ei(o),i=e.get(s);if(i!=null)return i;let a=yn(s,t);return e.set(s,a),a}function yw(r,t){return r==null?{}:{prefix:Jl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Pi(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Pi(n.key,n.value,t),Pi(o.key,o.value,t)))}}var Ri=class{peerId;datastore;lock;addressFilter;constructor(t,e={}){this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=Yl({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(wn(t))}async delete(t){if(this.peerId.equals(t))throw new D("Cannot delete self peer");await this.datastore.delete(wn(t))}async load(t){let e=await this.datastore.get(wn(t));return yn(t,e)}async save(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ni(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,s,n,o)}async patch(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ni(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async merge(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Ni(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async*all(t){let e=new ce;for await(let{key:n,value:o}of this.datastore.query(yw(t??{},e))){let s=Pi(n,o,e);s.id.equals(this.peerId)||(yield s)}}async#t(t){try{let e=await this.datastore.get(wn(t)),n=yn(t,e);return{existingBuf:e,existingPeer:n}}catch(e){if(e.name!=="NotFoundError")throw e}return{}}async#e(t,e,n,o){let s=gn.encode(e);return n!=null&&it(s,n)?{peer:yn(t,s),previous:o,updated:!1}:(await this.datastore.put(wn(t),s),{peer:yn(t,s),previous:o,updated:!0})}};var Di=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Ri(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await bo(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await pn.openAndCertify(t,Er.DOMAIN),o=ei(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=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 pn.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:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};var Mi=class extends Error{constructor(t="Not Found"){super(t),this.name="NotFoundError"}};function ww(r){return r[Symbol.asyncIterator]!=null}function bw(r){if(ww(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Ql=bw;function xw(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var ap=xw;function vw(r){return r[Symbol.asyncIterator]!=null}function Ew(r,t){let e=0;if(vw(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=ap(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var _r=Ew;function Aw(r){return r[Symbol.asyncIterator]!=null}function Sw(r,t){return Aw(r)?async function*(){yield*(await bo(r)).sort(t)}():function*(){yield*bo(r).sort(t)}()}var tu=Sw;function _w(r){return r[Symbol.asyncIterator]!=null}function Bw(r,t){return _w(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var eu=Bw;var Ui=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await Ql(this.putMany(t,n)),t=[],await Ql(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=_r(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tu(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=_r(n,()=>o++>=s)}return t.limit!=null&&(n=eu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=_r(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tu(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=_r(n,()=>s++>=o)}return t.limit!=null&&(n=eu(n,t.limit)),n}};var Oi=class extends Ui{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new Mi;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new Sr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new Sr(t)}};function cp(r,t){let e;return function(){let n=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(n,t)}}var Iw=r=>r;function ru(r,t){let e=r.getPeerId();return e!=null&&ge(e).equals(t)&&(r=r.decapsulate(ot(`/p2p/${t.toString()}`))),r}var Fi=class{log;components;listen;announce;observed;announceFilter;constructor(t,e={}){let{listen:n=[],announce:o=[]}=e;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=e.announceFilter??Iw,this._updatePeerStoreAddresses=cp(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([e,n])=>n.confident).map(([e])=>ot(e))).map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>ot(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>ot(t))}getObservedAddrs(){return Array.from(this.observed).map(([t])=>ot(t))}addObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString();this.observed.has(e)||this.observed.set(e,{confident:!1})}confirmObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString(),o=(this.observed.get(e)??{confident:!1}).confident;this.observed.set(e,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(t){t=ru(t,this.components.peerId);let e=t.toString();this.observed.delete(e)}getAddresses(){let t=this.getAnnounceAddrs().map(n=>n.toString());t.length===0&&(t=this.components.transportManager.getAddrs().map(n=>n.toString())),t=t.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let e=new Set(t);return this.announceFilter(Array.from(e).map(n=>ot(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var lp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(lp||(lp={}));var Vi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Hi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},xo=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},vo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},$i=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Ki=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},qi=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Eo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Br=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Ao=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},zi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},Ir=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},So=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Gi=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var nu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=Ei())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Ko(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Cw=["metrics","connectionProtector","dns"],Tw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function up(r={}){let t=new nu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Tw.includes(o)){let i=t.components[o];if(i==null&&!Cw.includes(o))throw new Vi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function fp(r){let t={};for(let e of Object.values(r.components))for(let n of Lw(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Nw(e))if(t[n]!==!0)throw new Hi(`Service "${Pw(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Lw(r){return Array.isArray(r?.[In])?r[In]:[]}function Nw(r){return Array.isArray(r?.[Da])?r[Da]:[]}function Pw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function hp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{let e=t.stringTuples();return e[0][0]===4||e[0][0]===41?!!fi(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var dp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rw=new WeakMap;function Dw({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(dp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(dp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Rw.set(l,()=>{c(s),s=null,i()}),l}}var Mw=Dw(),pp=Mw;var Wi=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}};var ji=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new ou}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Wi("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 pp(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},ou=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function Zi(r){if(Po(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:ge(e),r.forEach(n=>{if(!Qe(n))throw new Pr("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=ge(o);if(t?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Uw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function mp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Uw;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var gp="last-dial-failure",yp="last-dial-success";var Xi=100,Yi=50;var wp={maxConnections:Xi,allow:[]},Ji=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??wp.maxConnections,this.allow=e.allow??wp.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),t.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new ce;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await mp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Qi=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},bn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Qi(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Qi(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var su=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ta(r={}){return Ow(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ow(r,t){t=t??{};let e=t.onEnd,n=new bn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new bn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new bn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new su)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(g){return m.end(g),e!=null&&(e(g),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var iu=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function xn(r,t,e,n){let o=new iu(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ea=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function nr(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ea(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ea(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ra=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new be)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var na=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Fw(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,tt(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new be),this.cleanup())}async join(t={}){let e=new ra(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await nr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var vn=class extends ve{concurrency;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){e?.signal?.throwIfAborted();let n=new na(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new be)}),this.clear()}async onEmpty(t){this.size!==0&&await xn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await xn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await xn(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ta({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new be("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var oa=class extends vn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function kr(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}async function bp(r,t){let e=!1;for(let o of un.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}var _o={addressSorter:fn,maxParallelDials:Yi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:yr}},sa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter??_o.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??_o.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??_o.maxDialQueueLength,this.dialTimeout=e.dialTimeout??_o.dialTimeout,this.connections=e.connections??new ce,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,tt(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(e.resolvers??{}))un.set(n,o);this.queue=new oa({concurrency:e.maxParallelDials??_o.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,tt(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=Zi(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new ft("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new ft("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Dr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new ft("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new ft("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new ft("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Dr("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[yp]: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:{[gp]: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 Rr(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:e.priority??uu,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal,onProgress:e.onProgress})}createDialAbortController(t){let e=kr([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,t]);return tt(1/0,e),e}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(l=>({multiaddr:ot(l),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Dr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Eo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let l=await this.components.peerStore.get(t);o.push(...l.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let l=await this.components.peerRouting.findPeer(t);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",t,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await bp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(t!=null){let l=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new 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 Eo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!ao.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ia=class extends vn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Bp=sr(Sp(),1);var Hw=Object.prototype.toString,$w=r=>Hw.call(r)==="[object Error]",Kw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function fu(r){return r&&$w(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Kw.has(r.message):!1}var hu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},_p=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function du(r,t){return new Promise((e,n)=>{t={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...t};let o=Bp.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof hu)throw c.originalError;if(c instanceof TypeError&&!fu(c))throw c;if(_p(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){_p(u,a,t),i(),n(u)}}})})}var aa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new ia({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,t.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(t){!this.started||!(await this.peerStore.get(t)).tags.has(Ra)||this.queue.has(t)||this.queue.add(async n=>{await du(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(n=>{this.log.error("failed to reconnect to %p",t,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(Ra)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};var uu=50,pu={maxConnections:Xi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},ca=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(t,e={}){if(this.maxConnections=e.maxConnections??pu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new ce,this.started=!1,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(e.allow??[]).map(n=>ot(n)),this.deny=(e.deny??[]).map(n=>ot(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??pu.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new ji({points:e.inboundConnectionThreshold??pu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Ji({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new sa(t,{addressSorter:e.addressSorter??fn,maxParallelDials:e.maxParallelDials??Yi,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??5e3,resolvers:e.resolvers??{dnsaddr:yr},connections:this.connections}),this.reconnectQueue=new aa({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,outbound:0};for(let e of this.connections.values())for(let n of e)n.direction==="inbound"?t.inbound++:t.outbound++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),await Du(this.dialQueue,this.reconnectQueue),this.started=!0,this.log("started")}async stop(){await Mu(this.reconnectQueue,this.dialQueue);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}let n=e.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(e):(s=!0,this.connections.set(n,[e])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t;if(!this.started)return;let n=e.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==e.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.isStarted())throw new xe("Not started");e.signal?.throwIfAborted();let{peerId:n}=Zi(t);if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new ft("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??uu}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>ot(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var En=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(t){this.timespan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timespan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var Gw=1.2,Ww=2,jw=2e3,la=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new En(t.interval??5e3),this.failure=new En(t.interval??5e3),this.next=new En(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Ww,this.timeoutMultiplier=t.timeoutMultiplier??Gw,this.minTimeout=t.minTimeout??jw,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=kr([t.signal,n]);return tt(1/0,o,n),o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var mu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=lt(),await nr(this.readNext.promise,e?.signal,e)}};function Ip(){return new mu}var ua=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var gu=class extends Error{code;constructor(t,e){super(t),this.code=e}},yu=class extends gu{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function fa(r,t){let e=Ip();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new wt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new yu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new wt:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new ua("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Zw=1e4,Xw="1.0.0",Yw="ping",Jw="ipfs",kp=32,Qw=!0,ha=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Jw}/${Yw}/${Xw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Zw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Qw,this.timeout=new la({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,tt(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=fa(o);e=Date.now(),await Promise.all([s.write(en(kp),{signal:n}),s.read(kp,{signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function tb(r){return r[Symbol.asyncIterator]!=null}function eb(...r){let t=[];for(let e of r)tb(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=ta({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Bo=eb;var da=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new xo("No content routers available");let n=this,o=new br;for await(let s of Bo(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new xo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new xe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new xe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var pa=globalThis.CustomEvent??Event;async function*wu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=lt(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new pa("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new pa("task-complete"))})}c=!0,o.dispatchEvent(new pa("task-complete"))}catch(p){u=p,o.dispatchEvent(new pa("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=lt(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var ma=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new vo("No peer routers available");if(t.toString()===this.peerId.toString())throw new $i("Should not try to find self");let n=this,o=Bo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Mo}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new vo("No peer routers available");let n=this,o=$l(1024);for await(let s of wu(async function*(){let i=Bo(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ga=class extends ve{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,tt(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,tt(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=kr([this.shutdownController.signal,t?.signal]);tt(1/0,e);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await xn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,tt(1/0,this.walkController.signal);let t=kr([this.walkController.signal,this.shutdownController.signal]);tt(1/0,t);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=en(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await nr(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var bu=32,xu=64,ya=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Ki(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t))throw new qi(`Handler already registered for protocol ${t}`);let o=wi.bind({ignoreUndefined:!0})({maxInboundStreams:bu,maxOutboundStreams:xu},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,e){if(e==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var vu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Cp(r){let{name:t,metrics:e}=r,n;return e!=null?n=new vu({name:t,metrics:e}):n=new Map,n}var wa=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=Cp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Oe.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new D("Transport must have a valid tag");if(this.transports.has(e))throw new D(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new Gi(`No transport available for address ${String(t)}`);return e?.onProgress?.(new ft("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new xe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(t),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){e.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Oe.NO_FATAL)throw new Br(`Transport (${n}) could not listen on any available address`)}if(e.length===this.transports.size){let n=`no valid addresses were provided for transports [${e.join(", ")}]`;if(this.faultTolerance===Oe.FATAL_ALL)throw new Br(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var Bt="/multistream/1.0.0";var ba=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},xa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},va=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,t={}){let e=fa(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ht(t.maxDataLength));let n=t?.lengthDecoder??se,o=t?.lengthEncoder??Ct;return{read:async i=>{let a=-1,c=new wt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new ba("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new va("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new xa("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new wt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new wt(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var rb=P(`
7
+ `);async function Tr(r,t,e){await r.write(t,e)}async function Tp(r,t,e){await r.writeV(t,e)}async function nb(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==rb[0])throw t.log.error("Invalid mss message - missing newline",e),new Vo("Missing newline");return e.sublist(0,-1)}async function or(r,t){let e=await nb(r,t);return H(e.subarray())}async function ko(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return ob(r,t[0],e);let n=Io(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',Bt,o);let s=P(`${Bt}
8
+ `),i=P(`${o}
9
+ `);await Tp(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await or(n,e);if(e.log.trace('select: read "%s"',a),a===Bt&&(e.log.trace("select: reading protocol response"),a=await or(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Tr(n,P(`${c}
10
+ `),e),e.log.trace("select: reading protocol response");let u=await or(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new Bn("protocol selection failed")}function ob(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=lt(),c=!1,u=!1,f=lt(),l=!1,d=!1,h=lt(),p=Io({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let x=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Bt,t,A.byteLength);let _=`${t}
11
+ `;yield new wt(Uint8Array.from([19]),P(`${Bt}
12
+ `),Ct(_.length),P(_),A).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Bt,t,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,v)})}x=!0}x||await m()}())};async function m(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await g()),l||(e.log.trace("optimistic: doing read protocol for %s stream",t),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',Bt,t),await p.writeV([P(`${Bt}
13
+ `),P(`${t}
14
+ `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',Bt,t)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let b=await or(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',b),b===Bt&&(b=await or(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',b,t),b!==t)throw new Bn("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(x=>{e.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(x=>{e.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await nr(Promise.all(x),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:t}}function Ea(r){return r[Symbol.asyncIterator]!=null}var Aa=r=>{let t=ht(r),e=It(t);return Ct(r,e),Aa.bytes=t,e};Aa.bytes=0;function Sa(r,t){t=t??{};let e=t.lengthEncoder??Aa;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ea(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Sa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Aa;return new wt(e(r.byteLength),r)};var _a=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ba=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ia=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Co=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var sb=8,ib=1024*1024*4,Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Su=r=>{let t=se(r);return Su.bytes=ht(t),t};Su.bytes=0;function Au(r,t){let e=new wt,n=Lr.LENGTH,o=-1,s=t?.lengthDecoder??Su,i=t?.maxLengthLength??sb,a=t?.maxDataLength??ib;function*c(){for(;e.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(e),o<0)throw new _a("Invalid message length");if(o>a)throw new Ba("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Lr.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new Ia("Message length length too long");break}throw u}if(n===Lr.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Lr.LENGTH}}}return Ea(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Co("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Co("Unexpected end of input")}()}Au.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Au(n,{...t??{},onLength:s=>{e=s}})};async function To(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Io(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await or(n,e);if(e.log.trace('handle: read "%s"',o),o===Bt){e.log.trace('handle: respond with "%s" for "%s"',Bt,o),await Tr(n,P(`${Bt}
15
+ `),e),e.log.trace('handle: responded with "%s" for "%s"',Bt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Tr(n,P(`${o}
16
+ `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new wt(...t.map(i=>Sa.single(P(`${i}
17
+ `))),P(`
18
+ `));e.log.trace('handle: respond with "%s" for %s',t,o),await Tr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log('handle: respond with "na" for "%s"',o),await Tr(n,P(`na
19
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var cb=500,_u=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ru]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Ro("the connection is being closed");if(this.status==="closed")throw new Do("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(cb);tt(1/0,e),t={...t,signal:e}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async e=>e.close(t))),this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(e=>{e.abort(t)}),this.log.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}};function Np(r){return new _u(r)}var lb=3e4;function ub(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return bu}function fb(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??xu}function Pp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var ka=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;events;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??2e3,this.events=t.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,e,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(t,e))throw new Ao(`The multiaddr connection is blocked by gater.${n}`)}async upgradeInbound(t,e){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new zi("connection denied");let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{t.abort(new Rr("inbound upgrade timeout"))};u.addEventListener("abort",f,{once:!0}),tt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new Ao("The multiaddr connection is blocked by gater.acceptConnection");this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the inbound connection upgrade");let l=t;if(e?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the inbound connection"),l=await d.protect(t))}try{if(o=l,e?.skipEncryption!==!0){e?.onProgress?.(new ft("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=t.remoteAddr.getPeerId();if(d==null)throw new Pr("inbound connection that skipped encryption must have a peer id");let h=ge(d);c="native",s=h}if(i=o,e?.muxerFactory!=null)a=e.muxerFactory;else if(this.streamMuxers.size>0){e?.onProgress?.(new ft("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.streamMuxers);a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,t,"denyInboundUpgradedConnection"),t.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:e?.limits})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await this.shouldBlockConnection(o,t,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the outbound connection upgrade");let f=t;if(e?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(t))}try{if(s=f,e?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,{...e,remotePeer:o}));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new Uo("Encryption was skipped but no peer id was passed");c="native",i=o}if(a=s,e?.muxerFactory!=null)u=e.muxerFactory;else if(this.streamMuxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.streamMuxers);u=l.muxerFactory,a=l.stream}}catch(l){throw t.log.error("failed to upgrade outbound connection",l),await t.close(l),l}return await this.shouldBlockConnection(i,t,"denyOutboundUpgradedConnection"),t.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:t,upgradedConn:a,muxerFactory:u,remotePeer:i,limits:e?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await To(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=ub(y,this.components.registrar);if(Pp(y,"inbound",l)===b){let x=new Ho(`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 Ir("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(lb);tt(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await ko(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=fb(b,this.components.registrar,m),x=Pp(b,"outbound",l);if(x>=w){let A=new $o(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new 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 Ir("Connection is not multiplexed")};return l=Np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting inbound connection using",s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection failed",o),new So(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("selecting outbound crypto protocol",n);try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %p using %s",e?.remotePeer,i),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %p failed",e?.remotePeer,o),new So(o.message)}}async _multiplexOutbound(t,e){let n=Array.from(e.keys());t.log("outbound selecting muxer %s",n);try{t.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",s);let i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing outbound connection",o),new Ir(String(o))}}async _multiplexInbound(t,e){let n=Array.from(e.keys());t.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing inbound connection",o),new Ir(String(o))}}};var Rp="1.9.4-2bbaf4361",Dp="libp2p";var Ca=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},tt(1/0,e),this.peerId=t.peerId,this.logger=t.logger??Ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=up({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:Dp,version:Rp},logger:this.logger,events:e,datastore:t.datastore??new Oi,connectionGater:hp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",new Di(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new ka(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new wa(this.components,t.transportManager)),this.configureComponent("connectionManager",new ca(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ha(this.components,t.connectionMonitor)),this.configureComponent("registrar",new ya(this.components)),this.configureComponent("addressManager",new Fi(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ma(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new da(this.components,{routers:i})),this.configureComponent("randomWalk",new ga(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[La]!=null&&(this.log("registering service %s for content routing",a),i.push(u[La])),u[Pa]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Pa])),u[Na]!=null&&(this.log("registering service %s for peer discovery",a),u[Na].addEventListener?.("peer",f=>{this.#t(f)}))}fp(o)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new br;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new D("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){Qe(t)&&(t=ge(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ft([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=nn(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function db(r={}){r.privateKey??=await Wh("Ed25519");let t=new Ca({...await Od(r),peerId:Yh(r.privateKey)});return r.start!==!1&&await t.start(),t}return Zp(pb);})();
21
20
  /*! Bundled license information:
22
21
 
23
22
  pvtsutils/build/index.js: