libp2p 1.8.2-f30e2ee8d → 1.8.3-0edbfe7af
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +13 -13
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +18 -18
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
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 tp=Object.create;var _o=Object.defineProperty;var rp=Object.getOwnPropertyDescriptor;var np=Object.getOwnPropertyNames;var op=Object.getPrototypeOf,sp=Object.prototype.hasOwnProperty;var _t=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)_o(r,t,{get:e[t],enumerable:!0})},jl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of np(e))!sp.call(r,o)&&o!==t&&_o(r,o,{get:()=>e[o],enumerable:!(n=rp(e,o))||n.enumerable});return r};var $t=(r,e,t)=>(t=r!=null?tp(op(r)):{},jl(e||!r||!r.__esModule?_o(t,"default",{value:r,enumerable:!0}):t,r)),ip=r=>jl(_o({},"__esModule",{value:!0}),r);var Ju=_t(rn=>{"use strict";var Og="[object ArrayBuffer]",Nt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Og}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}},rc="string",Ug=/^[0-9a-f]+$/i,Mg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fg=/^[a-zA-Z0-9-_]+$/,Go=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}},Yo=class r{static isHex(e){return typeof e===rc&&Ug.test(e)}static isBase64(e){return typeof e===rc&&Mg.test(e)}static isBase64Url(e){return typeof e===rc&&Fg.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 Go.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 Go.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,"")||""}};Yo.DEFAULT_UTF8_ENCODING="utf8";function Vg(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 Kg(...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 Hg(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}rn.BufferSourceConverter=Nt;rn.Convert=Yo;rn.assign=Vg;rn.combine=Kg;rn.isEqual=Hg});var dh=_t((ro,Fs)=>{(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,y=h.length-m,g=d,w=0,b=3432918353,x=461845907,v=0;v<y;v=v+4)w=h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24,w=o(w,b),w=s(w,15),w=o(w,x),g^=w,g=s(g,13),g=o(g,5)+3864292196;switch(w=0,m){case 3:w^=h[v+2]<<16;case 2:w^=h[v+1]<<8;case 1:w^=h[v],w=o(w,b),w=s(w,15),w=o(w,x),g^=w}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,y=h.length-m,g=d,w=d,b=d,x=d,v=0,S=0,_=0,R=0,$=597399067,q=2869860233,U=951274213,ee=2716044179,D=0;D<y;D=D+16)v=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,S=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,R=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,v=o(v,$),v=s(v,15),v=o(v,q),g^=v,g=s(g,19),g+=w,g=o(g,5)+1444728091,S=o(S,q),S=s(S,16),S=o(S,U),w^=S,w=s(w,17),w+=b,w=o(w,5)+197830471,_=o(_,U),_=s(_,17),_=o(_,ee),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,R=o(R,ee),R=s(R,18),R=o(R,$),x^=R,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(v=0,S=0,_=0,R=0,m){case 15:R^=h[D+14]<<16;case 14:R^=h[D+13]<<8;case 13:R^=h[D+12],R=o(R,ee),R=s(R,18),R=o(R,$),x^=R;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,U),_=s(_,17),_=o(_,ee),b^=_;case 8:S^=h[D+7]<<24;case 7:S^=h[D+6]<<16;case 6:S^=h[D+5]<<8;case 5:S^=h[D+4],S=o(S,q),S=s(S,16),S=o(S,U),w^=S;case 4:v^=h[D+3]<<24;case 3:v^=h[D+2]<<16;case 2:v^=h[D+1]<<8;case 1:v^=h[D],v=o(v,$),v=s(v,15),v=o(v,q),g^=v}return g^=h.length,w^=h.length,b^=h.length,x^=h.length,g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,g=i(g),w=i(w),b=i(b),x=i(x),g+=w,g+=b,g+=x,w+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>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,y=h.length-m,g=[0,d],w=[0,d],b=[0,0],x=[0,0],v=[2277735313,289559509],S=[1291169091,658871167],_=0;_<y;_=_+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,v),b=u(b,31),b=c(b,S),g=l(g,b),g=u(g,27),g=a(g,w),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,S),x=u(x,33),x=c(x,v),w=l(w,x),w=u(w,31),w=a(w,g),w=a(c(w,[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,S),x=u(x,33),x=c(x,v),w=l(w,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,v),b=u(b,31),b=c(b,S),g=l(g,b)}return g=l(g,[0,h.length]),w=l(w,[0,h.length]),g=a(g,w),w=a(w,g),g=p(g),w=p(w),g=a(g,w),w=a(w,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)},typeof ro<"u"?(typeof Fs<"u"&&Fs.exports&&(ro=Fs.exports=t),ro.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)})(ro)});var mh=_t((kv,ph)=>{ph.exports=dh()});var Fh=_t((a2,Kc)=>{"use strict";var dy=Object.prototype.hasOwnProperty,qe="~";function co(){}Object.create&&(co.prototype=Object.create(null),new co().__proto__||(qe=!1));function py(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Mh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new py(t,n||r,o),i=qe?qe+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Gs(r,e){--r._eventsCount===0?r._events=new co:delete r._events[e]}function Me(){this._events=new co,this._eventsCount=0}Me.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)dy.call(t,n)&&e.push(qe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Me.prototype.listeners=function(e){var t=qe?qe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Me.prototype.listenerCount=function(e){var t=qe?qe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Me.prototype.emit=function(e,t,n,o,s,i){var a=qe?qe+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var 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};Me.prototype.on=function(e,t,n){return Mh(this,e,t,n,!1)};Me.prototype.once=function(e,t,n){return Mh(this,e,t,n,!0)};Me.prototype.removeListener=function(e,t,n,o){var s=qe?qe+e:e;if(!this._events[s])return this;if(!t)return Gs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Gs(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:Gs(this,s)}return this};Me.prototype.removeAllListeners=function(e){var t;return e?(t=qe?qe+e:e,this._events[t]&&Gs(this,t)):(this._events=new co,this._eventsCount=0),this};Me.prototype.off=Me.prototype.removeListener;Me.prototype.addListener=Me.prototype.on;Me.prefixed=qe;Me.EventEmitter=Me;typeof Kc<"u"&&(Kc.exports=Me)});var ol=_t((RS,Jh)=>{"use strict";function Qh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function ky(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 Qh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Qh(new o,t)}}Jh.exports=ky});var sd=_t(ho=>{(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}(),ho.ip2long=i,ho.long2ip=a,ho.Netmask=r}).call(ho)});var wd=_t((DR,yd)=>{yd.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 _d=_t((QR,vd)=>{"use strict";vd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Td=_t((Id,Bd)=>{"use strict";var di=_d(),{hasOwnProperty:Sd}=Object.prototype,{propertyIsEnumerable:sw}=Object,vn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),iw=Id,Ad={concatArrays:!1,ignoreUndefined:!1},pi=r=>{let e=[];for(let t in r)Sd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)sw.call(r,n)&&e.push(n)}return e};function _n(r){return Array.isArray(r)?aw(r):di(r)?cw(r):r}function aw(r){let e=r.slice(0,0);return pi(r).forEach(t=>{vn(e,t,_n(r[t]))}),e}function cw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return pi(r).forEach(t=>{vn(e,t,_n(r[t]))}),e}var Rd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?vn(r,o,wl(r[o],e[o],n)):vn(r,o,_n(e[o])))}),r),lw=(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++)Sd.call(s,a)&&(i.push(String(a)),s===r?vn(n,o++,s[a]):vn(n,o++,_n(s[a])));n=Rd(n,s,pi(s).filter(a=>!i.includes(a)),t)}),n};function wl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?lw(r,e,t):!di(e)||!di(r)?_n(e):Rd(r,e,pi(e),t)}Bd.exports=function(...r){let e=wl(_n(Ad),this!==iw&&this||{},Ad),t={_:{}};for(let n of r)if(n!==void 0){if(!di(n))throw new TypeError("`"+n+"` is not an Option Object");t=wl(t,{_:n},e)}return t._}});var Dw={};ve(Dw,{createLibp2p:()=>Lw});var Xl=Symbol.for("@libp2p/connection");var Yi=Symbol.for("@libp2p/content-routing");var Wi=Symbol.for("@libp2p/peer-discovery");var Ao=Symbol.for("@libp2p/peer-id");function So(r){return r!=null&&!!r[Ao]}var ji=Symbol.for("@libp2p/peer-routing");var Zl="keep-alive";var Hw=Symbol.for("@libp2p/transport");var qt;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(qt||(qt={}));var zt=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??{}}},Ro=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 Io="ERR_TIMEOUT";var fe=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),fe(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 Zi(e,t))}},Xi=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Zi=globalThis.CustomEvent??Xi;function Ql(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var Qi=Symbol.for("@libp2p/service-capabilities"),Ji=Symbol.for("@libp2p/service-dependencies");var ec={};ve(ec,{Ed25519PrivateKey:()=>_r,Ed25519PublicKey:()=>Mn,generateKeyPair:()=>Lg,generateKeyPairFromSeed:()=>Qu,unmarshalEd25519PrivateKey:()=>kg,unmarshalEd25519PublicKey:()=>Ng});var oa={};ve(oa,{base58btc:()=>ie,base58flickr:()=>hp});var wb=new Uint8Array(0);function Jl(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 eu(r){return new TextEncoder().encode(r)}function tu(r){return new TextDecoder().decode(r)}function ap(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(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,y=0,g=0,w=d.length;g!==w&&d[g]===0;)g++,m++;for(var b=(w-g)*f+1>>>0,x=new Uint8Array(b);g!==w;){for(var v=d[g],S=0,_=b-1;(v!==0||S<y)&&_!==-1;_--,S++)v+=256*x[_]>>>0,x[_]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=S,g++}for(var R=b-y;R!==b&&x[R]===0;)R++;for(var $=c.repeat(m);R<b;++R)$+=r.charAt(x[R]);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 y=0,g=0;d[m]===c;)y++,m++;for(var w=(d.length-m)*u+1>>>0,b=new Uint8Array(w);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var v=0,S=w-1;(x!==0||v<g)&&S!==-1;S--,v++)x+=a*b[S]>>>0,b[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=v,m++}if(d[m]!==" "){for(var _=w-g;_!==w&&b[_]===0;)_++;for(var R=new Uint8Array(y+(w-_)),$=y;_!==w;)R[$++]=b[_++];return R}}}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 cp=ap,lp=cp,nu=lp;var ea=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")}},ta=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 ou(this,e)}},ra=class{decoders;constructor(e){this.decoders=e}or(e){return ou(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 ou(r,e){return new ra({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var na=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 ea(e,t,n),this.decoder=new ta(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new na(r,e,t,n)}function Gt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=nu(t,r);return Fr({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function up(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 fp(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 Fr({prefix:e,name:r,encode(o){return fp(o,n,t)},decode(o){return up(o,n,t,r)}})}var ie=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hp=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ia={};ve(ia,{identity:()=>Rt});var dp=au,su=128,pp=127,mp=~pp,gp=Math.pow(2,31);function au(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gp;)e[t++]=r&255|su,r/=128;for(;r∓)e[t++]=r&255|su,r>>>=7;return e[t]=r|0,au.bytes=t-n+1,e}var yp=sa,wp=128,iu=127;function sa(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw sa.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&iu)<<o:(i&iu)*Math.pow(2,o),o+=7}while(i>=wp);return sa.bytes=s-n,t}var bp=Math.pow(2,7),Ep=Math.pow(2,14),xp=Math.pow(2,21),vp=Math.pow(2,28),_p=Math.pow(2,35),Ap=Math.pow(2,42),Sp=Math.pow(2,49),Rp=Math.pow(2,56),Ip=Math.pow(2,63),Bp=function(r){return r<bp?1:r<Ep?2:r<xp?3:r<vp?4:r<_p?5:r<Ap?6:r<Sp?7:r<Rp?8:r<Ip?9:10},Tp={encode:dp,decode:yp,encodingLength:Bp},Cp=Tp,Tn=Cp;function Cn(r,e=0){return[Tn.decode(r,e),Tn.decode.bytes]}function Vr(r,e,t=0){return Tn.encode(r,e,t),e}function Kr(r){return Tn.encodingLength(r)}function dt(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Vr(r,s,0),Vr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function mr(r){let e=St(r),[t,n]=Cn(e),[o,s]=Cn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hr(t,o,i,e)}function cu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Jl(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var lu=0,kp="identity",uu=St;function Np(r){return dt(lu,uu(r))}var Rt={code:lu,name:kp,encode:uu,digest:Np};var la={};ve(la,{sha256:()=>Re,sha512:()=>Lp});function ca({name:r,code:e,encode:t}){return new aa(r,e,t)}var aa=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?dt(this.code,t):t.then(n=>dt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function hu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=ca({name:"sha2-256",code:18,encode:hu("SHA-256")}),Lp=ca({name:"sha2-512",code:19,encode:hu("SHA-512")});function te(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ot(r=0){return new Uint8Array(r)}function Le(r=0){return new Uint8Array(r)}function Ie(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Le(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var ua={};ve(ua,{base10:()=>Dp});var Dp=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var fa={};ve(fa,{base16:()=>Pp,base16upper:()=>Op});var Pp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Op=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ha={};ve(ha,{base2:()=>Up});var Up=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var da={};ve(da,{base256emoji:()=>Hp});var du=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}"),Mp=du.reduce((r,e,t)=>(r[t]=e,r),[]),Fp=du.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Vp(r){return r.reduce((e,t)=>(e+=Mp[t],e),"")}function Kp(r){let e=[];for(let t of r){let n=Fp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Hp=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:Vp,decode:Kp});var pa={};ve(pa,{base32:()=>Ge,base32hex:()=>Gp,base32hexpad:()=>Wp,base32hexpadupper:()=>jp,base32hexupper:()=>Yp,base32pad:()=>qp,base32padupper:()=>zp,base32upper:()=>$p,base32z:()=>Xp});var Ge=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$p=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qp=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zp=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gp=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yp=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wp=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jp=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xp=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ma={};ve(ma,{base36:()=>Zp,base36upper:()=>Qp});var Zp=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qp=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ya={};ve(ya,{base64:()=>kn,base64pad:()=>Jp,base64url:()=>ga,base64urlpad:()=>em});var kn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Jp=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ga=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),em=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var wa={};ve(wa,{base8:()=>tm});var tm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ba={};ve(ba,{identity:()=>rm});var rm=Fr({prefix:"\0",name:"identity",encode:r=>tu(r),decode:r=>eu(r)});var Gb=new TextEncoder,Yb=new TextDecoder;function pu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return im(t,Ea(r),e??ie.encoder);default:return am(t,Ea(r),e??Ge.encoder)}}var mu=new WeakMap;function Ea(r){let e=mu.get(r);if(e==null){let t=new Map;return mu.set(r,t),t}return e}var Je=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==cm)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=dt(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&&cu(e.multihash,n.multihash)}toString(e){return pu(this,e)}toJSON(){return{"/":pu(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??gu(n,o,s.bytes))}else if(t[lm]===!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!==Nn)throw new Error(`Version 0 CID must use dag-pb (code: ${Nn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=gu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Nn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=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 Hr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Cn(e.subarray(t));return t+=p,l},o=n(),s=Nn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=sm(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 Ea(s).set(n,e),s}};function sm(r,e){switch(r[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${r}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function im(r,e,t){let{prefix:n}=t;if(n!==ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function am(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Nn=112,cm=18;function gu(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Vr(r,s,0),Vr(e,s,n),s.set(t,o),s}var lm=Symbol.for("@ipld/js-cid/CID");var Yt={...ba,...ha,...wa,...ua,...fa,...pa,...ma,...oa,...ya,...da},lE={...la,...ia};function wu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var yu=wu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),xa=wu("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=Le(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),um={utf8:yu,"utf-8":yu,hex:Yt.base16,latin1:xa,ascii:xa,binary:xa,...Yt},To=um;function L(r,e="utf8"){let t=To[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function et(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function $r(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function fm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qr(r,...e){if(!fm(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 Co(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$r(r.outputLen),$r(r.blockLen)}function zr(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 bu(r,e){qr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var ko=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),st=(r,e)=>r<<32-e|r>>>e;var _E=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var hm=async()=>{};async function Eu(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 hm(),n+=s)}}function xu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Wt(r){return typeof r=="string"&&(r=xu(r)),qr(r),r}function va(...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}var Gr=class{clone(){return this._cloneInto()}},dm={}.toString;function vu(r,e){if(e!==void 0&&dm.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function No(r){let e=n=>r().update(Wt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Wr(r=32){if(ko&&typeof ko.getRandomValues=="function")return ko.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function pm(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 _u=(r,e,t)=>r&e^~r&t,Au=(r,e,t)=>r&e^r&t^e&t,jr=class extends Gr{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=Yr(this.buffer)}update(e){zr(this);let{view:t,buffer:n,blockLen:o}=this;e=Wt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Yr(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){zr(this),bu(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;pm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(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 Lo=BigInt(4294967295),_a=BigInt(32);function Su(r,e=!1){return e?{h:Number(r&Lo),l:Number(r>>_a&Lo)}:{h:Number(r>>_a&Lo)|0,l:Number(r&Lo)|0}}function mm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Su(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var gm=(r,e)=>BigInt(r>>>0)<<_a|BigInt(e>>>0),ym=(r,e,t)=>r>>>t,wm=(r,e,t)=>r<<32-t|e>>>t,bm=(r,e,t)=>r>>>t|e<<32-t,Em=(r,e,t)=>r<<32-t|e>>>t,xm=(r,e,t)=>r<<64-t|e>>>t-32,vm=(r,e,t)=>r>>>t-32|e<<64-t,_m=(r,e)=>e,Am=(r,e)=>r,Sm=(r,e,t)=>r<<t|e>>>32-t,Rm=(r,e,t)=>e<<t|r>>>32-t,Im=(r,e,t)=>e<<t-32|r>>>64-t,Bm=(r,e,t)=>r<<t-32|e>>>64-t;function Tm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Cm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),km=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Nm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Lm=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Dm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Pm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Om={fromBig:Su,split:mm,toBig:gm,shrSH:ym,shrSL:wm,rotrSH:bm,rotrSL:Em,rotrBH:xm,rotrBL:vm,rotr32H:_m,rotr32L:Am,rotlSH:Sm,rotlSL:Rm,rotlBH:Im,rotlBL:Bm,add:Tm,add3L:Cm,add3H:km,add4L:Nm,add4H:Lm,add5H:Pm,add5L:Dm},M=Om;var[Um,Mm]=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))),jt=new Uint32Array(80),Xt=new Uint32Array(80),Aa=class extends jr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah: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:y}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,y){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=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)jt[b]=e.getUint32(t),Xt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=jt[b-15]|0,v=Xt[b-15]|0,S=M.rotrSH(x,v,1)^M.rotrSH(x,v,8)^M.shrSH(x,v,7),_=M.rotrSL(x,v,1)^M.rotrSL(x,v,8)^M.shrSL(x,v,7),R=jt[b-2]|0,$=Xt[b-2]|0,q=M.rotrSH(R,$,19)^M.rotrBH(R,$,61)^M.shrSH(R,$,6),U=M.rotrSL(R,$,19)^M.rotrBL(R,$,61)^M.shrSL(R,$,6),ee=M.add4L(_,U,Xt[b-7],Xt[b-16]),D=M.add4H(ee,S,q,jt[b-7],jt[b-16]);jt[b]=D|0,Xt[b]=ee|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:y,Hh:g,Hl:w}=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),v=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),S=l&h^~l&m,_=p&d^~p&y,R=M.add5L(w,v,_,Mm[b],Xt[b]),$=M.add5H(R,g,x,S,Um[b],jt[b]),q=R|0,U=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),ee=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,Qe=o&i^o&c^i&c;g=m|0,w=y|0,m=h|0,y=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,$|0,q|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let I=M.add3L(q,ee,Qe);n=M.add3H(I,$,U,D),o=I|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:y}=M.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:g,l:w}=M.add(this.Hh|0,this.Hl|0,g|0,w|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,y,g,w)}roundClean(){jt.fill(0),Xt.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 Ln=No(()=>new Aa);var Po={};ve(Po,{abytes:()=>Xr,bitGet:()=>zm,bitLen:()=>qm,bitMask:()=>Dn,bitSet:()=>Gm,bytesToHex:()=>Bt,bytesToNumberBE:()=>Tt,bytesToNumberLE:()=>Qt,concatBytes:()=>Ct,createHmacDrbg:()=>Ia,ensureBytes:()=>le,equalBytes:()=>Hm,hexToBytes:()=>yr,hexToNumber:()=>Ra,isBytes:()=>Zt,numberToBytesBE:()=>Jt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>Tu,numberToVarBytesBE:()=>Km,utf8ToBytes:()=>$m,validateObject:()=>pt});var Bu=BigInt(0),Do=BigInt(1),Fm=BigInt(2);function Zt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Xr(r){if(!Zt(r))throw new Error("Uint8Array expected")}var Vm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){Xr(r);let e="";for(let t=0;t<r.length;t++)e+=Vm[r[t]];return e}function Tu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ra(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 Ru(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=Ru(r.charCodeAt(s)),a=Ru(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 Tt(r){return Ra(Bt(r))}function Qt(r){return Xr(r),Ra(Bt(Uint8Array.from(r).reverse()))}function Jt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Jt(r,e).reverse()}function Km(r){return yr(Tu(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(Zt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Ct(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Hm(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 $m(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function qm(r){let e;for(e=0;r>Bu;r>>=Do,e+=1);return e}function zm(r,e){return r>>BigInt(e)&Do}function Gm(r,e,t){return r|(t?Do:Bu)<<BigInt(e)}var Dn=r=>(Fm<<BigInt(r-1))-Do,Sa=r=>new Uint8Array(r),Iu=r=>Uint8Array.from(r);function Ia(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=Sa(r),o=Sa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Sa())=>{o=a(Iu([0]),l),n=a(),l.length!==0&&(o=a(Iu([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 Ym={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Zt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function pt(r,e,t={}){let n=(o,s,i)=>{let a=Ym[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 we=BigInt(0),re=BigInt(1),br=BigInt(2),Wm=BigInt(3),Ba=BigInt(4),Cu=BigInt(5),ku=BigInt(8),jm=BigInt(9),Xm=BigInt(16);function Q(r,e){let t=r%e;return t>=we?t:e+t}function Zm(r,e,t){if(t<=we||e<we)throw new Error("Expected power/modulo > 0");if(t===re)return we;let n=re;for(;e>we;)e&re&&(n=n*r%t),r=r*r%t,e>>=re;return n}function ne(r,e,t){let n=r;for(;e-- >we;)n*=n,n%=t;return n}function Oo(r,e){if(r===we||e<=we)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Q(r,e),n=e,o=we,s=re,i=re,a=we;for(;t!==we;){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!==re)throw new Error("invert: does not exist");return Q(o,e)}function Qm(r){let e=(r-re)/br,t,n,o;for(t=r-re,n=0;t%br===we;t/=br,n++);for(o=br;o<r&&Zm(o,e,r)!==r-re;o++);if(n===1){let i=(r+re)/Ba;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+re)/br;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,re<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function Jm(r){if(r%Ba===Wm){let e=(r+re)/Ba;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%ku===Cu){let e=(r-Cu)/ku;return function(n,o){let s=n.mul(o,br),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,br),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%Xm,Qm(r)}var Nu=(r,e)=>(Q(r,e)&re)===re,eg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ta(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=eg.reduce((n,o)=>(n[o]="function",n),e);return pt(r,t)}function tg(r,e,t){if(t<we)throw new Error("Expected power > 0");if(t===we)return r.ONE;if(t===re)return e;let n=r.ONE,o=e;for(;t>we;)t&re&&(n=r.mul(n,o)),o=r.sqr(o),t>>=re;return n}function rg(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 Ca(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Uo(r,e,t=!1,n={}){if(r<=we)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ca(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Jm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Dn(o),ZERO:we,ONE:re,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return we<=c&&c<r},is0:c=>c===we,isOdd:c=>(c&re)===re,neg:c=>Q(-c,r),eql:(c,u)=>c===u,sqr:c=>Q(c*c,r),add:(c,u)=>Q(c+u,r),sub:(c,u)=>Q(c-u,r),mul:(c,u)=>Q(c*u,r),pow:(c,u)=>tg(a,c,u),div:(c,u)=>Q(c*Oo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Oo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>rg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Jt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Qt(c):Tt(c)}});return Object.freeze(a)}function Lu(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 ka(r){let e=Lu(r);return e+Math.ceil(e/2)}function Du(r,e,t=!1){let n=r.length,o=Lu(e),s=ka(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Tt(r):Qt(r),a=Q(i,e-re)+re;return t?wr(a,o):Jt(a,o)}var og=BigInt(0),Na=BigInt(1);function Mo(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>og;)s&Na&&(i=i.add(a)),a=a.double(),s>>=Na;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],u=o,f=u;for(let l=0;l<i;l++){f=u,c.push(f);for(let p=1;p<a;p++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),u=r.ZERO,f=r.BASE,l=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let d=0;d<a;d++){let m=d*c,y=Number(i&l);i>>=h,y>c&&(y-=p,i+=Na);let g=m,w=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?f=f.add(t(b,s[g])):u=u.add(t(x,s[w]))}return{p:u,f}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,u=s.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&s.set(o,a(u))),this.wNAF(c,u,i)}}}function Pn(r){return Ta(r.Fp),pt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ca(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var it=BigInt(0),Ye=BigInt(1),Fo=BigInt(2),sg=BigInt(8),ig={zip215:!0};function ag(r){let e=Pn(r);return pt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Pu(r){let e=ag(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Fo<<BigInt(a*8)-Ye,f=t.create,l=e.uvRatio||((B,A)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(A))}}catch{return{isValid:!1,value:it}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,A,k)=>{if(A.length||k)throw new Error("Contexts/pre-hash are not supported");return B}),d=B=>typeof B=="bigint"&&it<B,m=(B,A)=>d(B)&&d(A)&&B<A,y=B=>B===it||m(B,u);function g(B,A){if(m(B,A))return B;throw new Error(`Expected valid scalar < ${A}, got ${typeof B} ${B}`)}function w(B){return B===it?B:g(B,n)}let b=new Map;function x(B){if(!(B instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(A,k,P,O){if(this.ex=A,this.ey=k,this.ez=P,this.et=O,!y(A))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(P))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof v)throw new Error("extended point not allowed");let{x:k,y:P}=A||{};if(!y(k)||!y(P))throw new Error("invalid affine point");return new v(k,P,Ye,f(k*P))}static normalizeZ(A){let k=t.invertBatch(A.map(P=>P.ez));return A.map((P,O)=>P.toAffine(k[O])).map(v.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,b.delete(this)}assertValidity(){let{a:A,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:O,ez:K,et:H}=this,W=f(P*P),G=f(O*O),Y=f(K*K),pe=f(Y*Y),ae=f(W*A),Ae=f(Y*f(ae+G)),Se=f(pe+f(k*f(W*G)));if(Ae!==Se)throw new Error("bad point: equation left != right (1)");let ye=f(P*O),Ne=f(K*H);if(ye!==Ne)throw new Error("bad point: equation left != right (2)")}equals(A){x(A);let{ex:k,ey:P,ez:O}=this,{ex:K,ey:H,ez:W}=A,G=f(k*W),Y=f(K*O),pe=f(P*W),ae=f(H*O);return G===Y&&pe===ae}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:A}=e,{ex:k,ey:P,ez:O}=this,K=f(k*k),H=f(P*P),W=f(Fo*f(O*O)),G=f(A*K),Y=k+P,pe=f(f(Y*Y)-K-H),ae=G+H,Ae=ae-W,Se=G-H,ye=f(pe*Ae),Ne=f(ae*Se),vt=f(pe*Se),pr=f(Ae*ae);return new v(ye,Ne,pr,vt)}add(A){x(A);let{a:k,d:P}=e,{ex:O,ey:K,ez:H,et:W}=this,{ex:G,ey:Y,ez:pe,et:ae}=A;if(k===BigInt(-1)){let Hl=f((K-O)*(Y+G)),$l=f((K+O)*(Y-G)),Gi=f($l-Hl);if(Gi===it)return this.double();let ql=f(H*Fo*ae),zl=f(W*Fo*pe),Gl=zl+ql,Yl=$l+Hl,Wl=zl-ql,Zd=f(Gl*Gi),Qd=f(Yl*Wl),Jd=f(Gl*Wl),ep=f(Gi*Yl);return new v(Zd,Qd,ep,Jd)}let Ae=f(O*G),Se=f(K*Y),ye=f(W*P*ae),Ne=f(H*pe),vt=f((O+K)*(G+Y)-Ae-Se),pr=Ne-ye,Bn=Ne+ye,Kl=f(Se-k*Ae),Yd=f(vt*pr),Wd=f(Bn*Kl),jd=f(vt*Kl),Xd=f(pr*Bn);return new v(Yd,Wd,Xd,jd)}subtract(A){return this.add(A.negate())}wNAF(A){return R.wNAFCached(this,b,A,v.normalizeZ)}multiply(A){let{p:k,f:P}=this.wNAF(g(A,n));return v.normalizeZ([k,P])[0]}multiplyUnsafe(A){let k=w(A);return k===it?_:this.equals(_)||k===Ye?this:this.equals(S)?this.wNAF(k).p:R.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(A){let{ex:k,ey:P,ez:O}=this,K=this.is0();A==null&&(A=K?sg:t.inv(O));let H=f(k*A),W=f(P*A),G=f(O*A);if(K)return{x:it,y:Ye};if(G!==Ye)throw new Error("invZ was invalid");return{x:H,y:W}}clearCofactor(){let{h:A}=e;return A===Ye?this:this.multiplyUnsafe(A)}static fromHex(A,k=!1){let{d:P,a:O}=e,K=t.BYTES;A=le("pointHex",A,K);let H=A.slice(),W=A[K-1];H[K-1]=W&-129;let G=Qt(H);G===it||(k?g(G,u):g(G,t.ORDER));let Y=f(G*G),pe=f(Y-Ye),ae=f(P*Y-O),{isValid:Ae,value:Se}=l(pe,ae);if(!Ae)throw new Error("Point.fromHex: invalid y coordinate");let ye=(Se&Ye)===Ye,Ne=(W&128)!==0;if(!k&&Se===it&&Ne)throw new Error("Point.fromHex: x=0 and x_0=1");return Ne!==ye&&(Se=f(-Se)),v.fromAffine({x:Se,y:G})}static fromPrivateKey(A){return U(A).point}toRawBytes(){let{x:A,y:k}=this.toAffine(),P=wr(k,t.BYTES);return P[P.length-1]|=A&Ye?128:0,P}toHex(){return Bt(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ye,f(e.Gx*e.Gy)),v.ZERO=new v(it,Ye,Ye,it);let{BASE:S,ZERO:_}=v,R=Mo(v,a*8);function $(B){return Q(B,n)}function q(B){return $(Qt(B))}function U(B){let A=a;B=le("private key",B,A);let k=le("hashed private key",s(B),2*A),P=p(k.slice(0,A)),O=k.slice(A,2*A),K=q(P),H=S.multiply(K),W=H.toRawBytes();return{head:P,prefix:O,scalar:K,point:H,pointBytes:W}}function ee(B){return U(B).pointBytes}function D(B=new Uint8Array,...A){let k=Ct(...A);return q(s(h(k,le("context",B),!!o)))}function Qe(B,A,k={}){B=le("message",B),o&&(B=o(B));let{prefix:P,scalar:O,pointBytes:K}=U(A),H=D(k.context,P,B),W=S.multiply(H).toRawBytes(),G=D(k.context,W,K,B),Y=$(H+G*O);w(Y);let pe=Ct(W,wr(Y,t.BYTES));return le("result",pe,a*2)}let I=ig;function N(B,A,k,P=I){let{context:O,zip215:K}=P,H=t.BYTES;B=le("signature",B,2*H),A=le("message",A),o&&(A=o(A));let W=Qt(B.slice(H,2*H)),G,Y,pe;try{G=v.fromHex(k,K),Y=v.fromHex(B.slice(0,H),K),pe=S.multiplyUnsafe(W)}catch{return!1}if(!K&&G.isSmallOrder())return!1;let ae=D(O,Y.toRawBytes(),G.toRawBytes(),A);return Y.add(G.multiplyUnsafe(ae)).subtract(pe).clearCofactor().equals(v.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:Qe,verify:N,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>i(t.BYTES),precompute(B=8,A=v.BASE){return A._setWindowSize(B),A.multiply(BigInt(3)),A}}}}var La=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ou=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GE=BigInt(0),cg=BigInt(1),Uu=BigInt(2),YE=BigInt(3),lg=BigInt(5),ug=BigInt(8);function fg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=La,a=r*r%s*r%s,c=ne(a,Uu,s)*a%s,u=ne(c,cg,s)*r%s,f=ne(u,lg,s)*u%s,l=ne(f,e,s)*f%s,p=ne(l,t,s)*l%s,h=ne(p,n,s)*p%s,d=ne(h,o,s)*h%s,m=ne(d,o,s)*h%s,y=ne(m,e,s)*f%s;return{pow_p_5_8:ne(y,Uu,s)*r%s,b2:a}}function hg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function dg(r,e){let t=La,n=Q(e*e*e,t),o=Q(n*n*e,t),s=fg(r*o).pow_p_5_8,i=Q(r*n*s,t),a=Q(e*i*i,t),c=i,u=Q(i*Ou,t),f=a===r,l=a===Q(-r,t),p=a===Q(-r*Ou,t);return f&&(i=c),(l||p)&&(i=u),Nu(i,t)&&(i=Q(-i,t)),{isValid:f||l,value:i}}var pg=Uo(La,void 0,!0),mg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:pg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ug,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ln,randomBytes:Wr,adjustScalarBytes:hg,uvRatio:dg},Zr=Pu(mg);var Qr=32,kt=64,Vo=32;function Mu(){let r=Zr.utils.randomPrivateKey(),e=Zr.getPublicKey(r);return{privateKey:Hu(r,e),publicKey:e}}function Fu(r){if(r.length!==Vo)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=Zr.getPublicKey(e);return{privateKey:Hu(e,t),publicKey:t}}function Vu(r,e){let t=r.subarray(0,Vo);return Zr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Ku(r,e,t){return Zr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Hu(r,e){let t=new Uint8Array(kt);for(let n=0;n<Vo;n++)t[n]=r[n],t[Vo+n]=e[n];return t}var Fe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Da={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function $u(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Fe.get();t*=8;async function c(l,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 y;if(p.length===0){y=await a.subtle.importKey("jwk",Da,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Da,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(w,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,l);return Ie([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),y={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",Da,{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 w=await a.subtle.decrypt(y,g,m);return new Uint8Array(w)}return{encrypt:c,decrypt:u}}async function Jr(r,e){let n=await $u().encrypt(r,e);return kn.encode(n)}var wg=Math.pow(2,7),bg=Math.pow(2,14),Eg=Math.pow(2,21),Pa=Math.pow(2,28),Oa=Math.pow(2,35),Ua=Math.pow(2,42),Ma=Math.pow(2,49),X=128,De=127;function me(r){if(r<wg)return 1;if(r<bg)return 2;if(r<Eg)return 3;if(r<Pa)return 4;if(r<Oa)return 5;if(r<Ua)return 6;if(r<Ma)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fa(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|X,r/=128;case 7:e[t++]=r&255|X,r/=128;case 6:e[t++]=r&255|X,r/=128;case 5:e[t++]=r&255|X,r/=128;case 4:e[t++]=r&255|X,r>>>=7;case 3:e[t++]=r&255|X,r>>>=7;case 2:e[t++]=r&255|X,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function xg(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|X),r/=128;case 7:e.set(t++,r&255|X),r/=128;case 6:e.set(t++,r&255|X),r/=128;case 5:e.set(t++,r&255|X),r/=128;case 4:e.set(t++,r&255|X),r>>>=7;case 3:e.set(t++,r&255|X),r>>>=7;case 2:e.set(t++,r&255|X),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Va(r,e){let t=r[e],n=0;if(n+=t&De,t<X||(t=r[e+1],n+=(t&De)<<7,t<X)||(t=r[e+2],n+=(t&De)<<14,t<X)||(t=r[e+3],n+=(t&De)<<21,t<X)||(t=r[e+4],n+=(t&De)*Pa,t<X)||(t=r[e+5],n+=(t&De)*Oa,t<X)||(t=r[e+6],n+=(t&De)*Ua,t<X)||(t=r[e+7],n+=(t&De)*Ma,t<X))return n;throw new RangeError("Could not decode varint")}function vg(r,e){let t=r.get(e),n=0;if(n+=t&De,t<X||(t=r.get(e+1),n+=(t&De)<<7,t<X)||(t=r.get(e+2),n+=(t&De)<<14,t<X)||(t=r.get(e+3),n+=(t&De)<<21,t<X)||(t=r.get(e+4),n+=(t&De)*Pa,t<X)||(t=r.get(e+5),n+=(t&De)*Oa,t<X)||(t=r.get(e+6),n+=(t&De)*Ua,t<X)||(t=r.get(e+7),n+=(t&De)*Ma,t<X))return n;throw new RangeError("Could not decode varint")}function Pe(r,e,t=0){return e==null&&(e=Le(me(r))),e instanceof Uint8Array?Fa(r,e,t):xg(r,e,t)}function at(r,e=0){return r instanceof Uint8Array?Va(r,e):vg(r,e)}var Ka=new Float32Array([-0]),er=new Uint8Array(Ka.buffer);function qu(r,e,t){Ka[0]=r,e[t]=er[0],e[t+1]=er[1],e[t+2]=er[2],e[t+3]=er[3]}function zu(r,e){return er[0]=r[e],er[1]=r[e+1],er[2]=r[e+2],er[3]=r[e+3],Ka[0]}var Ha=new Float64Array([-0]),Oe=new Uint8Array(Ha.buffer);function Gu(r,e,t){Ha[0]=r,e[t]=Oe[0],e[t+1]=Oe[1],e[t+2]=Oe[2],e[t+3]=Oe[3],e[t+4]=Oe[4],e[t+5]=Oe[5],e[t+6]=Oe[6],e[t+7]=Oe[7]}function Yu(r,e){return Oe[0]=r[e],Oe[1]=r[e+1],Oe[2]=r[e+2],Oe[3]=r[e+3],Oe[4]=r[e+4],Oe[5]=r[e+5],Oe[6]=r[e+6],Oe[7]=r[e+7],Ha[0]}var _g=BigInt(Number.MAX_SAFE_INTEGER),Ag=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 xr;if(e<_g&&e>Ag)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>Wu&&(o=0n,++n>Wu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return xr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):xr}},xr=new We(0,0);xr.toBigInt=function(){return 0n};xr.zzEncode=xr.zzDecode=function(){return this};xr.length=function(){return 1};var Wu=4294967296n;function ju(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 Xu(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 $a(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 ct(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ko(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var qa=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,ct(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 ct(this,4);return Ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ct(this,4);return Ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ct(this,4);let e=zu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ct(this,4);let e=Yu(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 ct(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Xu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ct(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ct(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 ct(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 ct(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 ct(this,8);let e=Ko(this.buf,this.pos+=4),t=Ko(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=Va(this.buf,this.pos);return this.pos+=me(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 za(r){return new qa(r instanceof Uint8Array?r:r.subarray())}function Ve(r,e,t){let n=za(r);return e.decode(n,void 0,t)}function Ga(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Le(i);o+i>e&&(n=Le(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var vr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ya(){}var ja=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Sg=Ga();function Rg(r){return globalThis.Buffer!=null?Le(r):Sg(r)}var Un=class{len;head;tail;states;constructor(){this.len=0,this.head=new vr(Ya,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new vr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Xa((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(Ho,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(Ho,t.length(),t)}uint64Number(e){return this._push(Fa,me(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(Ho,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(Ho,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Wa,1,e?1:0)}fixed32(e){return this._push(On,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(On,4,t.lo)._push(On,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(On,4,t.lo)._push(On,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(qu,4,e)}double(e){return this._push(Gu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Wa,1,0):this.uint32(t)._push(Bg,t,e)}string(e){let t=ju(e);return t!==0?this.uint32(t)._push($a,t,e):this._push(Wa,1,0)}fork(){return this.states=new ja(this),this.head=this.tail=new vr(Ya,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new vr(Ya,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=Rg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Wa(r,e,t){e[t]=r&255}function Ig(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Xa=class extends vr{next;constructor(e,t){super(Ig,e,t),this.next=void 0}};function Ho(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 On(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 Bg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Tg,e,r),this},Un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Cg,e,r),this});function Tg(r,e,t){e.set(r,t)}function Cg(r,e,t){r.length<40?$a(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Za(){return new Un}function Ke(r,e){let t=Za();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var en;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(en||(en={}));function $o(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Qa(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 $o("enum",en.VARINT,t,n)}function He(r,e){return $o("message",en.LENGTH_DELIMITED,r,e)}var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(oe||(oe={}));var Ja;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Ja||(Ja={}));(function(r){r.codec=()=>Qa(Ja)})(oe||(oe={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(mt||(mt={}));var gt;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),oe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=oe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(gt||(gt={}));var Mn=class{_key;constructor(e){this._key=tn(e,Qr)}verify(e,t){return Ku(this._key,t,e)}marshal(){return this._key}get bytes(){return mt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},_r=class{_key;_publicKey;constructor(e,t){this._key=tn(e,kt),this._publicKey=tn(t,Qr)}sign(e){return Vu(this._key,e)}get public(){return new Mn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:oe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Rt.digest(this.public.bytes);return ie.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Jr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function kg(r){if(r.length>kt){r=tn(r,kt+Qr);let n=r.subarray(0,kt),o=r.subarray(kt,r.length);return new _r(n,o)}r=tn(r,kt);let e=r.subarray(0,kt),t=r.subarray(Qr);return new _r(e,t)}function Ng(r){return r=tn(r,Qr),new Mn(r)}async function Lg(){let{privateKey:r,publicKey:e}=Mu();return new _r(r,e)}async function Qu(r){let{privateKey:e,publicKey:t}=Fu(r);return new _r(e,t)}function tn(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=To[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var uc={};ve(uc,{MAX_RSA_KEY_SIZE:()=>Xn,RsaPrivateKey:()=>an,RsaPublicKey:()=>jn,fromJwk:()=>i0,generateKeyPair:()=>a0,unmarshalRsaPrivateKey:()=>cc,unmarshalRsaPublicKey:()=>s0});function yt(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Wr(r)}var or={};ve(or,{exportToPem:()=>e0,importFromPem:()=>t0,jwkToPkcs1:()=>Xg,jwkToPkix:()=>Qg,pkcs1ToJwk:()=>jg,pkixToJwk:()=>Zg});var zo=class extends Gr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Co(e);let n=Wt(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),qr(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()}},Fn=(r,e,t)=>new zo(r,e).update(t).digest();Fn.create=(r,e)=>new zo(r,e);function Dg(r,e,t,n){Co(r);let o=vu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if($r(s),$r(i),$r(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wt(e),u=Wt(t),f=new Uint8Array(i),l=Fn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Pg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function tc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=Dg(r,e,t,n),f,l=new Uint8Array(4),p=Yr(l),h=new Uint8Array(c.outputLen);for(let d=1,m=0;m<s;d++,m+=c.outputLen){let y=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),y.set(h.subarray(0,y.length)),await Eu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<y.length;g++)y[g]^=h[g]})}return Pg(c,u,a,f,h)}var z=$t(Ju());function Ar(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function tr(r,e,t=-1){let n=t,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 Wo(...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 nc(){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=Ar(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,Ar(s,8)-n}function ef(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(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 tf(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function ze(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var t1=Math.log(2);function jo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function oc(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 Kn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return oc(this.items)}},Vn=[new Uint8Array([1])],rf="0123456789";var on="",ut=new ArrayBuffer(0),sc=new Uint8Array(0),Hn="EndOfContent",of="OCTET STRING",sf="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?z.BufferSourceConverter.toUint8Array(s.valueHex):sc}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",ut)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:z.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=on,warnings:n=[],valueBeforeDecode:o=sc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=z.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:z.Convert.ToHex(this.valueBeforeDecodeView)}}};Lt.NAME="baseBlock";var Ue=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'")}};Ue.NAME="valueBlock";var Xo=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?z.BufferSourceConverter.toUint8Array(e.valueHex):sc,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",ut}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=tr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!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=Ar(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Xo.NAME="identificationBlock";var Zo=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=z.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=Ar(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=tr(this.length,8);if(o.byteLength>127)return this.error="Too big length",ut;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}}};Zo.NAME="lengthBlock";var T={},Be=class extends Lt{constructor({name:e=on,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Xo(o),this.lenBlock=new Zo(o),this.valueBlock=s?new s(o):new Ue(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Kn;t||af(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?ut:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():z.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return tf(t,n)}};Be.NAME="BaseBlock";function af(r){if(r instanceof T.Constructed)for(let e of r.valueBlock.value)af(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Qo=class extends Be{constructor({value:e=on,...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}'`}};Qo.NAME="BaseStringBlock";var Jo=class extends Ut(Ue){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Jo.NAME="PrimitiveValueBlock";var cf,es=class extends Be{constructor(e={}){super(e,Jo),this.idBlock.isConstructed=!1}};cf=es;T.Primitive=cf;es.NAME="PRIMITIVE";function qg(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 Ls(r,e=0,t=r.length){let n=e,o=new Be({},Ue),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=Be;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=T.EndOfContent;break;case 1:c=T.Boolean;break;case 2:c=T.Integer;break;case 3:c=T.BitString;break;case 4:c=T.OctetString;break;case 5:c=T.Null;break;case 6:c=T.ObjectIdentifier;break;case 10:c=T.Enumerated;break;case 12:c=T.Utf8String;break;case 13:c=T.RelativeObjectIdentifier;break;case 14:c=T.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=T.Sequence;break;case 17:c=T.Set;break;case 18:c=T.NumericString;break;case 19:c=T.PrintableString;break;case 20:c=T.TeletexString;break;case 21:c=T.VideotexString;break;case 22:c=T.IA5String;break;case 23:c=T.UTCTime;break;case 24:c=T.GeneralizedTime;break;case 25:c=T.GraphicString;break;case 26:c=T.VisibleString;break;case 27:c=T.GeneralString;break;case 28:c=T.UniversalString;break;case 29:c=T.CharacterString;break;case 30:c=T.BmpString;break;case 31:c=T.DATE;break;case 32:c=T.TimeOfDay;break;case 33:c=T.DateTime;break;case 34:c=T.Duration;break;default:{let u=o.idBlock.isConstructed?new T.Constructed:new T.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?T.Constructed:T.Primitive}return o=qg(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 sn(r){if(!r.byteLength){let e=new Be({},Ue);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ls(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function zg(r,e){return r?1:e}var wt=class extends Ue{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);if(!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(;zg(this.isIndefiniteForm,n)>0;){let i=Ls(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===Hn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Hn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Kn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ut:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wt.NAME="ConstructedValueBlock";var lf,rr=class extends Be{constructor(e={}){super(e,wt),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 fp=Object.create;var Ro=Object.defineProperty;var hp=Object.getOwnPropertyDescriptor;var dp=Object.getOwnPropertyNames;var pp=Object.getPrototypeOf,mp=Object.prototype.hasOwnProperty;var _t=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)Ro(r,t,{get:e[t],enumerable:!0})},ou=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dp(e))!mp.call(r,o)&&o!==t&&Ro(r,o,{get:()=>e[o],enumerable:!(n=hp(e,o))||n.enumerable});return r};var pr=(r,e,t)=>(t=r!=null?fp(pp(r)):{},ou(e||!r||!r.__esModule?Ro(t,"default",{value:r,enumerable:!0}):t,r)),gp=r=>ou(Ro({},"__esModule",{value:!0}),r);var lf=_t(nn=>{"use strict";var Yg="[object ArrayBuffer]",Nt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Yg}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}},hc="string",Wg=/^[0-9a-f]+$/i,jg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Xg=/^[a-zA-Z0-9-_]+$/,jo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Nt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},et=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}},Xo=class r{static isHex(e){return typeof e===hc&&Wg.test(e)}static isBase64(e){return typeof e===hc&&jg.test(e)}static isBase64Url(e){return typeof e===hc&&Xg.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 et.toString(n,!0);case"utf16":case"utf16be":return et.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 et.fromString(e,!0);case"utf16":case"utf16be":return et.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 jo.fromString(e);case"utf16":case"utf16be":return et.fromString(e);case"utf16le":case"usc2":return et.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return jo.toString(e);case"utf16":case"utf16be":return et.toString(e);case"utf16le":case"usc2":return et.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 et.toString(e,t)}static FromUtf16String(e,t=!1){return et.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,"")||""}};Xo.DEFAULT_UTF8_ENCODING="utf8";function Zg(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 Qg(...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 Jg(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}nn.BufferSourceConverter=Nt;nn.Convert=Xo;nn.assign=Zg;nn.combine=Qg;nn.isEqual=Jg});var _h=_t((no,Hs)=>{(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 no<"u"?(typeof Hs<"u"&&Hs.exports&&(no=Hs.exports=t),no.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)})(no)});var Sh=_t((Hv,Ah)=>{Ah.exports=_h()});var jh=_t((w2,Zc)=>{"use strict";var Ay=Object.prototype.hasOwnProperty,He="~";function lo(){}Object.create&&(lo.prototype=Object.create(null),new lo().__proto__||(He=!1));function Sy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Wh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Sy(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 js(r,e){--r._eventsCount===0?r._events=new lo:delete r._events[e]}function Oe(){this._events=new lo,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ay.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 Wh(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Wh(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 js(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&js(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:js(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&js(this,t)):(this._events=new lo,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=He;Oe.EventEmitter=Oe;typeof Zc<"u"&&(Zc.exports=Oe)});var ud=_t((US,ld)=>{"use strict";function cd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Hy(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 cd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),cd(new o,t)}}ld.exports=Hy});var gd=_t(po=>{(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}(),po.ip2long=i,po.long2ip=a,po.Netmask=r}).call(po)});var Td=_t((zR,Bd)=>{Bd.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 Dd=_t((lI,Ld)=>{"use strict";Ld.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Vd=_t((Md,Fd)=>{"use strict";var gi=Dd(),{hasOwnProperty:Od}=Object.prototype,{propertyIsEnumerable:gw}=Object,_n=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),yw=Md,Pd={concatArrays:!1,ignoreUndefined:!1},yi=r=>{let e=[];for(let t in r)Od.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)gw.call(r,n)&&e.push(n)}return e};function An(r){return Array.isArray(r)?ww(r):gi(r)?bw(r):r}function ww(r){let e=r.slice(0,0);return yi(r).forEach(t=>{_n(e,t,An(r[t]))}),e}function bw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return yi(r).forEach(t=>{_n(e,t,An(r[t]))}),e}var Ud=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?_n(r,o,Il(r[o],e[o],n)):_n(r,o,An(e[o])))}),r),Ew=(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++)Od.call(s,a)&&(i.push(String(a)),s===r?_n(n,o++,s[a]):_n(n,o++,An(s[a])));n=Ud(n,s,yi(s).filter(a=>!i.includes(a)),t)}),n};function Il(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Ew(r,e,t):!gi(e)||!gi(r)?An(e):Ud(r,e,yi(e),t)}Fd.exports=function(...r){let e=Il(An(Pd),this!==yw&&this||{},Pd),t={_:{}};for(let n of r)if(n!==void 0){if(!gi(n))throw new TypeError("`"+n+"` is not an Option Object");t=Il(t,{_:n},e)}return t._}});var zw={};ve(zw,{createLibp2p:()=>qw});var su=Symbol.for("@libp2p/connection");var ta=Symbol.for("@libp2p/content-routing");var ra=Symbol.for("@libp2p/peer-discovery");var Io=Symbol.for("@libp2p/peer-id");function Bo(r){return r!=null&&!!r[Io]}var na=Symbol.for("@libp2p/peer-routing");var iu="keep-alive";var Jw=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??{}}},To=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 Co="ERR_TIMEOUT";var ue=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),ue(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 oa(e,t))}},oa=globalThis.CustomEvent;function au(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var sa=Symbol.for("@libp2p/service-capabilities"),ia=Symbol.for("@libp2p/service-dependencies");var uc={};ve(uc,{Ed25519PrivateKey:()=>Ar,Ed25519PublicKey:()=>Fn,generateKeyPair:()=>qg,generateKeyPairFromSeed:()=>cf,unmarshalEd25519PrivateKey:()=>Hg,unmarshalEd25519PublicKey:()=>$g});var fa={};ve(fa,{base58btc:()=>ie,base58flickr:()=>vp});var Tb=new Uint8Array(0);function cu(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 lu(r){return new TextEncoder().encode(r)}function uu(r){return new TextDecoder().decode(r)}function yp(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 wp=yp,bp=wp,hu=bp;var aa=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")}},ca=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 du(this,e)}},la=class{decoders;constructor(e){this.decoders=e}or(e){return du(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 du(r,e){return new la({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ua=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 aa(e,t,n),this.decoder=new ca(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Vr({name:r,prefix:e,encode:t,decode:n}){return new ua(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=hu(t,r);return Vr({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function Ep(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 xp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Vr({prefix:e,name:r,encode(o){return xp(o,n,t)},decode(o){return Ep(o,n,t,r)}})}var ie=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vp=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var da={};ve(da,{identity:()=>Rt});var _p=gu,pu=128,Ap=127,Sp=~Ap,Rp=Math.pow(2,31);function gu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Rp;)e[t++]=r&255|pu,r/=128;for(;r&Sp;)e[t++]=r&255|pu,r>>>=7;return e[t]=r|0,gu.bytes=t-n+1,e}var Ip=ha,Bp=128,mu=127;function ha(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ha.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&mu)<<o:(i&mu)*Math.pow(2,o),o+=7}while(i>=Bp);return ha.bytes=s-n,t}var Tp=Math.pow(2,7),Cp=Math.pow(2,14),kp=Math.pow(2,21),Np=Math.pow(2,28),Lp=Math.pow(2,35),Dp=Math.pow(2,42),Pp=Math.pow(2,49),Op=Math.pow(2,56),Up=Math.pow(2,63),Mp=function(r){return r<Tp?1:r<Cp?2:r<kp?3:r<Np?4:r<Lp?5:r<Dp?6:r<Pp?7:r<Op?8:r<Up?9:10},Fp={encode:_p,decode:Ip,encodingLength:Mp},Vp=Fp,Tn=Vp;function Cn(r,e=0){return[Tn.decode(r,e),Tn.decode.bytes]}function Kr(r,e,t=0){return Tn.encode(r,e,t),e}function Hr(r){return Tn.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=Hr(r),o=n+Hr(t),s=new Uint8Array(o+t);return Kr(r,s,0),Kr(t,s,n),s.set(e,o),new $r(r,t,e,s)}function mr(r){let e=St(r),[t,n]=Cn(e),[o,s]=Cn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new $r(t,o,i,e)}function yu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&cu(r.bytes,t.bytes)}}var $r=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var wu=0,Kp="identity",bu=St;function Hp(r){return pt(wu,bu(r))}var Rt={code:wu,name:Kp,encode:bu,digest:Hp};var ga={};ve(ga,{sha256:()=>Se,sha512:()=>$p});function ma({name:r,code:e,encode:t}){return new pa(r,e,t)}var pa=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?pt(this.code,t):t.then(n=>pt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function xu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Se=ma({name:"sha2-256",code:18,encode:xu("SHA-256")}),$p=ma({name:"sha2-512",code:19,encode:xu("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 ot(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 ya={};ve(ya,{base10:()=>qp});var qp=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var wa={};ve(wa,{base16:()=>zp,base16upper:()=>Gp});var zp=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Gp=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ba={};ve(ba,{base2:()=>Yp});var Yp=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ea={};ve(Ea,{base256emoji:()=>Qp});var vu=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}"),Wp=vu.reduce((r,e,t)=>(r[t]=e,r),[]),jp=vu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Xp(r){return r.reduce((e,t)=>(e+=Wp[t],e),"")}function Zp(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 Qp=Vr({prefix:"\u{1F680}",name:"base256emoji",encode:Xp,decode:Zp});var xa={};ve(xa,{base32:()=>Ye,base32hex:()=>rm,base32hexpad:()=>om,base32hexpadupper:()=>sm,base32hexupper:()=>nm,base32pad:()=>em,base32padupper:()=>tm,base32upper:()=>Jp,base32z:()=>im});var Ye=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jp=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),em=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tm=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rm=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nm=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),om=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),sm=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),im=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var va={};ve(va,{base36:()=>am,base36upper:()=>cm});var am=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cm=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Aa={};ve(Aa,{base64:()=>kn,base64pad:()=>lm,base64url:()=>_a,base64urlpad:()=>um});var kn=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lm=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_a=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),um=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Sa={};ve(Sa,{base8:()=>fm});var fm=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ra={};ve(Ra,{identity:()=>hm});var hm=Vr({prefix:"\0",name:"identity",encode:r=>uu(r),decode:r=>lu(r)});var nE=new TextEncoder,oE=new TextDecoder;function _u(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return gm(t,Ia(r),e??ie.encoder);default:return ym(t,Ia(r),e??Ye.encoder)}}var Au=new WeakMap;function Ia(r){let e=Au.get(r);if(e==null){let t=new Map;return Au.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!==Nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wm)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=pt(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&&yu(e.multihash,n.multihash)}toString(e){return _u(this,e)}toJSON(){return{"/":_u(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??Su(n,o,s.bytes))}else if(t[bm]===!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!==Nn)throw new Error(`Version 0 CID must use dag-pb (code: ${Nn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Su(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Nn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=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 $r(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]=Cn(e.subarray(t));return t+=p,l},o=n(),s=Nn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=mm(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 Ia(s).set(n,e),s}};function mm(r,e){switch(r[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${r}`)]}case ie.prefix:{let t=e??ie;return[ie.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 gm(r,e,t){let{prefix:n}=t;if(n!==ie.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 ym(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Nn=112,wm=18;function Su(r,e,t){let n=Hr(r),o=n+Hr(e),s=new Uint8Array(o+t.byteLength);return Kr(r,s,0),Kr(e,s,n),s.set(t,o),s}var bm=Symbol.for("@ipld/js-cid/CID");var zt={...Ra,...ba,...Sa,...ya,...wa,...xa,...va,...fa,...Aa,...Ea},EE={...ga,...da};function Iu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ru=Iu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ba=Iu("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}),Em={utf8:Ru,"utf-8":Ru,hex:zt.base16,latin1:Ba,ascii:Ba,binary:Ba,...zt},No=Em;function L(r,e="utf8"){let t=No[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 qr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function xm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function zr(r,...e){if(!xm(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 Lo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");qr(r.outputLen),qr(r.blockLen)}function Gr(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 Bu(r,e){zr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Do=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Wr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),st=(r,e)=>r<<32-e|r>>>e;var DE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var vm=async()=>{};async function Tu(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 vm(),n+=s)}}function Cu(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=Cu(r)),zr(r),r}function Ta(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];zr(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 Yr=class{clone(){return this._cloneInto()}},_m={}.toString;function ku(r,e){if(e!==void 0&&_m.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Po(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 jr(r=32){if(Do&&typeof Do.getRandomValues=="function")return Do.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Am(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 Nu=(r,e,t)=>r&e^~r&t,Lu=(r,e,t)=>r&e^r&t^e&t,Xr=class extends Yr{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=Wr(this.buffer)}update(e){Gr(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=Wr(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){Gr(this),Bu(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;Am(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Wr(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 Oo=BigInt(4294967295),Ca=BigInt(32);function Du(r,e=!1){return e?{h:Number(r&Oo),l:Number(r>>Ca&Oo)}:{h:Number(r>>Ca&Oo)|0,l:Number(r&Oo)|0}}function Sm(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}=Du(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Rm=(r,e)=>BigInt(r>>>0)<<Ca|BigInt(e>>>0),Im=(r,e,t)=>r>>>t,Bm=(r,e,t)=>r<<32-t|e>>>t,Tm=(r,e,t)=>r>>>t|e<<32-t,Cm=(r,e,t)=>r<<32-t|e>>>t,km=(r,e,t)=>r<<64-t|e>>>t-32,Nm=(r,e,t)=>r>>>t-32|e<<64-t,Lm=(r,e)=>e,Dm=(r,e)=>r,Pm=(r,e,t)=>r<<t|e>>>32-t,Om=(r,e,t)=>e<<t|r>>>32-t,Um=(r,e,t)=>e<<t-32|r>>>64-t,Mm=(r,e,t)=>r<<t-32|e>>>64-t;function Fm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Vm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Km=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Hm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),$m=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,qm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),zm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Gm={fromBig:Du,split:Sm,toBig:Rm,shrSH:Im,shrSL:Bm,rotrSH:Tm,rotrSL:Cm,rotrBH:km,rotrBL:Nm,rotr32H:Lm,rotr32L:Dm,rotlSH:Pm,rotlSL:Om,rotlBH:Um,rotlBL:Mm,add:Fm,add3L:Vm,add3H:Km,add4L:Hm,add4H:$m,add5H:zm,add5L:qm},M=Gm;var[Ym,Wm]=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),ka=class extends Xr{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,_,Wm[b],Wt[b]),$=M.add5H(I,g,x,R,Ym[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 Ln=Po(()=>new ka);var Mo={};ve(Mo,{aInRange:()=>qe,abool:()=>it,abytes:()=>Zr,bitGet:()=>tg,bitLen:()=>eg,bitMask:()=>Pn,bitSet:()=>rg,bytesToHex:()=>Bt,bytesToNumberBE:()=>Tt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>Oa,ensureBytes:()=>ce,equalBytes:()=>Qm,hexToBytes:()=>yr,hexToNumber:()=>Pa,inRange:()=>Dn,isBytes:()=>jt,memoized:()=>br,notImplemented:()=>og,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>Uu,numberToVarBytesBE:()=>Zm,utf8ToBytes:()=>Jm,validateObject:()=>mt});var Da=BigInt(0),Uo=BigInt(1),jm=BigInt(2);function jt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!jt(r))throw new Error("Uint8Array expected")}function it(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var Xm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){Zr(r);let e="";for(let t=0;t<r.length;t++)e+=Xm[r[t]];return e}function Uu(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Pa(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 Pu(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=Pu(r.charCodeAt(s)),a=Pu(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 Tt(r){return Pa(Bt(r))}function Xt(r){return Zr(r),Pa(Bt(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 Zm(r){return yr(Uu(r))}function ce(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];Zr(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 Qm(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 Jm(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Na=r=>typeof r=="bigint"&&Da<=r;function Dn(r,e,t){return Na(r)&&Na(e)&&Na(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Dn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function eg(r){let e;for(e=0;r>Da;r>>=Uo,e+=1);return e}function tg(r,e){return r>>BigInt(e)&Uo}function rg(r,e,t){return r|(t?Uo:Da)<<BigInt(e)}var Pn=r=>(jm<<BigInt(r-1))-Uo,La=r=>new Uint8Array(r),Ou=r=>Uint8Array.from(r);function Oa(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=La(r),o=La(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=La())=>{o=a(Ou([0]),l),n=a(),l.length!==0&&(o=a(Ou([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 ng={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 mt(r,e,t={}){let n=(o,s,i)=>{let a=ng[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 og=()=>{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),sg=BigInt(3),Ua=BigInt(4),Mu=BigInt(5),Fu=BigInt(8),ig=BigInt(9),ag=BigInt(16);function X(r,e){let t=r%e;return t>=ge?t:e+t}function cg(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 Fo(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 lg(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&&cg(o,e,r)!==r-ee;o++);if(n===1){let i=(r+ee)/Ua;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 ug(r){if(r%Ua===sg){let e=(r+ee)/Ua;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%Fu===Mu){let e=(r-Mu)/Fu;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%ag,lg(r)}var Vu=(r,e)=>(X(r,e)&ee)===ee,fg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ma(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=fg.reduce((n,o)=>(n[o]="function",n),e);return mt(r,t)}function hg(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 dg(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 Fa(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Vo(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Fa(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=ug(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Pn(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)=>hg(a,c,u),div:(c,u)=>X(c*Fo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Fo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>dg(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):Tt(c)}});return Object.freeze(a)}function Ku(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 Va(r){let e=Ku(r);return e+Math.ceil(e/2)}function Hu(r,e,t=!1){let n=r.length,o=Ku(e),s=Va(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Tt(r):Xt(r),a=X(i,e-ee)+ee;return t?wr(a,o):Zt(a,o)}var mg=BigInt(0),Ka=BigInt(1),Ha=new WeakMap,$u=new WeakMap;function Ko(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>mg;)i&Ka&&(a=a.add(c)),c=c.double(),i>>=Ka;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+=Ka);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=$u.get(s)||1,u=Ha.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Ha.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),$u.set(s,i),Ha.delete(s)}}}function On(r){return Ma(r.Fp),mt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Fa(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var at=BigInt(0),ze=BigInt(1),Ho=BigInt(2),gg=BigInt(8),yg={zip215:!0};function wg(r){let e=On(r);return mt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function qu(r){let e=wg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=Ho<<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:at}}}),p=e.adjustScalarBytes||(S=>S),h=e.domain||((S,v,B)=>{if(it("phflag",B),v.length||B)throw new Error("Contexts/pre-hash are not supported");return S});function d(S,v){qe("coordinate "+S,v,at,u)}function m(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=br((S,v)=>{let{ex:B,ey:T,ez:P}=S,O=S.is0();v==null&&(v=O?gg:t.inv(P));let U=f(B*v),z=f(T*v),H=f(P*v);if(O)return{x:at,y:ze};if(H!==ze)throw new Error("invZ was invalid");return{x:U,y:z}}),g=br(S=>{let{a:v,d:B}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:T,ey:P,ez:O,et:U}=S,z=f(T*T),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(B*f(z*H)));if($e!==Ee)throw new Error("bad point: equation left != right (1)");let me=f(T*P),rt=f(O*U);if(me!==rt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,B,T,P){this.ex=v,this.ey=B,this.ez=T,this.et=P,d("x",v),d("y",B),d("z",T),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:B,y:T}=v||{};return d("x",B),d("y",T),new y(B,T,ze,f(B*T))}static normalizeZ(v){let B=t.invertBatch(v.map(T=>T.ez));return v.map((T,P)=>T.toAffine(B[P])).map(y.fromAffine)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){g(this)}equals(v){m(v);let{ex:B,ey:T,ez:P}=this,{ex:O,ey:U,ez:z}=v,H=f(B*z),G=f(O*P),oe=f(T*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:B,ey:T,ez:P}=this,O=f(B*B),U=f(T*T),z=f(Ho*f(P*P)),H=f(v*O),G=B+T,oe=f(f(G*G)-O-U),se=H+U,$e=se-z,Ee=H-U,me=f(oe*$e),rt=f(se*Ee),xe=f(oe*Ee),nt=f($e*se);return new y(me,rt,nt,xe)}add(v){m(v);let{a:B,d:T}=e,{ex:P,ey:O,ez:U,et:z}=this,{ex:H,ey:G,ez:oe,et:se}=v;if(B===BigInt(-1)){let Zl=f((O-P)*(G+H)),Ql=f((O+P)*(G-H)),ea=f(Ql-Zl);if(ea===at)return this.double();let Jl=f(U*Ho*se),eu=f(z*Ho*oe),tu=eu+Jl,ru=Ql+Zl,nu=eu-Jl,ap=f(tu*ea),cp=f(ru*nu),lp=f(tu*nu),up=f(ea*ru);return new y(ap,cp,up,lp)}let $e=f(P*H),Ee=f(O*G),me=f(z*T*se),rt=f(U*oe),xe=f((P+O)*(H+G)-$e-Ee),nt=rt-me,dr=rt+me,Bn=f(Ee-B*$e),So=f(xe*nt),op=f(dr*Bn),sp=f(xe*Bn),ip=f(nt*dr);return new y(So,op,ip,sp)}subtract(v){return this.add(v.negate())}wNAF(v){return A.wNAFCached(this,v,y.normalizeZ)}multiply(v){let B=v;qe("scalar",B,ze,n);let{p:T,f:P}=this.wNAF(B);return y.normalizeZ([T,P])[0]}multiplyUnsafe(v){let B=v;return qe("scalar",B,at,n),B===at?x:this.equals(x)||B===ze?this:this.equals(b)?this.wNAF(B).p:A.unsafeLadder(this,B)}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,B=!1){let{d:T,a:P}=e,O=t.BYTES;v=ce("pointHex",v,O),it("zip215",B);let U=v.slice(),z=v[O-1];U[O-1]=z&-129;let H=Xt(U),G=B?u:t.ORDER;qe("pointHex.y",H,at,G);let oe=f(H*H),se=f(oe-ze),$e=f(T*oe-P),{isValid:Ee,value:me}=l(se,$e);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let rt=(me&ze)===ze,xe=(z&128)!==0;if(!B&&me===at&&xe)throw new Error("Point.fromHex: x=0 and x_0=1");return xe!==rt&&(me=f(-me)),y.fromAffine({x:me,y:H})}static fromPrivateKey(v){return I(v).point}toRawBytes(){let{x:v,y:B}=this.toAffine(),T=wr(B,t.BYTES);return T[T.length-1]|=v&ze?128:0,T}toHex(){return Bt(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),y.ZERO=new y(at,ze,ze,at);let{BASE:b,ZERO:x}=y,A=Ko(y,a*8);function R(S){return X(S,n)}function _(S){return R(Xt(S))}function I(S){let v=a;S=ce("private key",S,v);let B=ce("hashed private key",s(S),2*v),T=p(B.slice(0,v)),P=B.slice(v,2*v),O=_(T),U=b.multiply(O),z=U.toRawBytes();return{head:T,prefix:P,scalar:O,point:U,pointBytes:z}}function $(S){return I(S).pointBytes}function V(S=new Uint8Array,...v){let B=Ct(...v);return _(s(h(B,ce("context",S),!!o)))}function K(S,v,B={}){S=ce("message",S),o&&(S=o(S));let{prefix:T,scalar:P,pointBytes:O}=I(v),U=V(B.context,T,S),z=b.multiply(U).toRawBytes(),H=V(B.context,z,O,S),G=R(U+H*P);qe("signature.s",G,at,n);let oe=Ct(z,wr(G,t.BYTES));return ce("result",oe,a*2)}let Q=yg;function D(S,v,B,T=Q){let{context:P,zip215:O}=T,U=t.BYTES;S=ce("signature",S,2*U),v=ce("message",v),O!==void 0&&it("zip215",O),o&&(v=o(v));let z=Xt(S.slice(U,2*U)),H,G,oe;try{H=y.fromHex(B,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 $a=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),zu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),nx=BigInt(0),bg=BigInt(1),Gu=BigInt(2),ox=BigInt(3),Eg=BigInt(5),xg=BigInt(8);function vg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=$a,a=r*r%s*r%s,c=te(a,Gu,s)*a%s,u=te(c,bg,s)*r%s,f=te(u,Eg,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,Gu,s)*r%s,b2:a}}function _g(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Ag(r,e){let t=$a,n=X(e*e*e,t),o=X(n*n*e,t),s=vg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*zu,t),f=a===r,l=a===X(-r,t),p=a===X(-r*zu,t);return f&&(i=c),(l||p)&&(i=u),Vu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Sg=Vo($a,void 0,!0),Rg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Sg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:xg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ln,randomBytes:jr,adjustScalarBytes:_g,uvRatio:Ag},Qr=qu(Rg);var Jr=32,kt=64,$o=32;function Yu(){let r=Qr.utils.randomPrivateKey(),e=Qr.getPublicKey(r);return{privateKey:Zu(r,e),publicKey:e}}function Wu(r){if(r.length!==$o)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=Qr.getPublicKey(e);return{privateKey:Zu(e,t),publicKey:t}}function ju(r,e){let t=r.subarray(0,$o);return Qr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Xu(r,e,t){return Qr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Zu(r,e){let t=new Uint8Array(kt);for(let n=0;n<$o;n++)t[n]=r[n],t[$o+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 qa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Qu(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",qa,{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",qa,{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",qa,{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 en(r,e){let n=await Qu().encrypt(r,e);return kn.encode(n)}var Tg=Math.pow(2,7),Cg=Math.pow(2,14),kg=Math.pow(2,21),za=Math.pow(2,28),Ga=Math.pow(2,35),Ya=Math.pow(2,42),Wa=Math.pow(2,49),W=128,Ne=127;function de(r){if(r<Tg)return 1;if(r<Cg)return 2;if(r<kg)return 3;if(r<za)return 4;if(r<Ga)return 5;if(r<Ya)return 6;if(r<Wa)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 Ng(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 Xa(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)*za,t<W)||(t=r[e+5],n+=(t&Ne)*Ga,t<W)||(t=r[e+6],n+=(t&Ne)*Ya,t<W)||(t=r[e+7],n+=(t&Ne)*Wa,t<W))return n;throw new RangeError("Could not decode varint")}function Lg(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)*za,t<W)||(t=r.get(e+5),n+=(t&Ne)*Ga,t<W)||(t=r.get(e+6),n+=(t&Ne)*Ya,t<W)||(t=r.get(e+7),n+=(t&Ne)*Wa,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):Ng(r,e,t)}function ct(r,e=0){return r instanceof Uint8Array?Xa(r,e):Lg(r,e)}var Za=new Float32Array([-0]),Qt=new Uint8Array(Za.buffer);function Ju(r,e,t){Za[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function ef(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],Za[0]}var Qa=new Float64Array([-0]),De=new Uint8Array(Qa.buffer);function tf(r,e,t){Qa[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 rf(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],Qa[0]}var Dg=BigInt(Number.MAX_SAFE_INTEGER),Pg=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<Dg&&e>Pg)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>nf&&(o=0n,++n>nf&&(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 nf=4294967296n;function of(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 sf(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 Ja(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 lt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function qo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ec=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,lt(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 lt(this,4);return qo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw lt(this,4);return qo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw lt(this,4);let e=ef(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw lt(this,4);let e=rf(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 lt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return sf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw lt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw lt(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 lt(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 lt(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 lt(this,8);let e=qo(this.buf,this.pos+=4),t=qo(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=Xa(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 tc(r){return new ec(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=tc(r);return e.decode(n,void 0,t)}function rc(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 nc(){}var sc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Og=rc();function Ug(r){return globalThis.Buffer!=null?ke(r):Og(r)}var Mn=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(nc,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 ic((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(zo,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(zo,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(zo,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(zo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(oc,1,e?1:0)}fixed32(e){return this._push(Un,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Un,4,t.lo)._push(Un,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Un,4,t.lo)._push(Un,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(Ju,4,e)}double(e){return this._push(tf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(oc,1,0):this.uint32(t)._push(Fg,t,e)}string(e){let t=of(e);return t!==0?this.uint32(t)._push(Ja,t,e):this._push(oc,1,0)}fork(){return this.states=new sc(this),this.head=this.tail=new _r(nc,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(nc,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=Ug(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function oc(r,e,t){e[t]=r&255}function Mg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ic=class extends _r{next;constructor(e,t){super(Mg,e,t),this.next=void 0}};function zo(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 Un(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 Fg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Mn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Vg,e,r),this},Mn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Kg,e,r),this});function Vg(r,e,t){e.set(r,t)}function Kg(r,e,t){r.length<40?Ja(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function ac(){return new Mn}function Fe(r,e){let t=ac();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var tn;(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"})(tn||(tn={}));function Go(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function cc(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 Go("enum",tn.VARINT,t,n)}function Ve(r,e){return Go("message",tn.LENGTH_DELIMITED,r,e)}var re;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(re||(re={}));var lc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(lc||(lc={}));(function(r){r.codec=()=>cc(lc)})(re||(re={}));var gt;(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())})(gt||(gt={}));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 Fn=class{_key;constructor(e){this._key=rn(e,Jr)}verify(e,t){return Xu(this._key,t,e)}marshal(){return this._key}get bytes(){return gt.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=rn(e,kt),this._publicKey=rn(t,Jr)}sign(e){return ju(this._key,e)}get public(){return new Fn(this._publicKey)}marshal(){return this._key}get bytes(){return yt.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 ie.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return en(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Hg(r){if(r.length>kt){r=rn(r,kt+Jr);let n=r.subarray(0,kt),o=r.subarray(kt,r.length);return new Ar(n,o)}r=rn(r,kt);let e=r.subarray(0,kt),t=r.subarray(Jr);return new Ar(e,t)}function $g(r){return r=rn(r,Jr),new Fn(r)}async function qg(){let{privateKey:r,publicKey:e}=Yu();return new Ar(r,e)}async function cf(r){let{privateKey:e,publicKey:t}=Wu(r);return new Ar(e,t)}function rn(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=No[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ec={};ve(Ec,{MAX_RSA_KEY_SIZE:()=>Zn,RsaPrivateKey:()=>cn,RsaPublicKey:()=>Xn,fromJwk:()=>y0,generateKeyPair:()=>w0,unmarshalRsaPrivateKey:()=>wc,unmarshalRsaPublicKey:()=>g0});function wt(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return jr(r)}var rr={};ve(rr,{exportToPem:()=>f0,importFromPem:()=>h0,jwkToPkcs1:()=>a0,jwkToPkix:()=>l0,pkcs1ToJwk:()=>i0,pkixToJwk:()=>c0});var Wo=class extends Yr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Lo(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 Gr(this),this.iHash.update(e),this}digestInto(e){Gr(this),zr(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()}},Vn=(r,e,t)=>new Wo(r,e).update(t).digest();Vn.create=(r,e)=>new Wo(r,e);function zg(r,e,t,n){Lo(r);let o=ku({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(qr(s),qr(i),qr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gt(e),u=Gt(t),f=new Uint8Array(i),l=Vn.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Gg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function fc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=zg(r,e,t,n),f,l=new Uint8Array(4),p=Wr(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 Tu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<w.length;g++)w[g]^=h[g]})}return Gg(c,u,a,f,h)}var q=pr(lf());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 Zo(...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 dc(){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 uf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=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 ff(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 h1=Math.log(2);function Qo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function pc(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 Hn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return pc(this.items)}},Kn=[new Uint8Array([1])],hf="0123456789";var sn="",ft=new ArrayBuffer(0),mc=new Uint8Array(0),$n="EndOfContent",pf="OCTET STRING",mf="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):mc}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",ft)}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=sn,warnings:n=[],valueBeforeDecode:o=mc}={}){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 Jo=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):mc,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",ft}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}}};Jo.NAME="identificationBlock";var es=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",ft;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}}};es.NAME="lengthBlock";var C={},Ie=class extends Lt{constructor({name:e=sn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Jo(o),this.lenBlock=new es(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 Hn;t||gf(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?ft: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 ff(t,n)}};Ie.NAME="BaseBlock";function gf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)gf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ts=class extends Ie{constructor({value:e=sn,...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}'`}};ts.NAME="BaseStringBlock";var rs=class extends Ut(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};rs.NAME="PrimitiveValueBlock";var yf,ns=class extends Ie{constructor(e={}){super(e,rs),this.idBlock.isConstructed=!1}};yf=ns;C.Primitive=yf;ns.NAME="PRIMITIVE";function t0(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 Os(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=t0(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 an(r){if(!r.byteLength){let e=new Ie({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Os(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function r0(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(;r0(this.isIndefiniteForm,n)>0;){let i=Os(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===$n)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===$n?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Hn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ft: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 wf,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(`
|
|
3
3
|
`).map(o=>` ${o}`).join(`
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
6
|
-
`)}`:`${t} :`}};lf=rr;T.Constructed=lf;rr.NAME="CONSTRUCTED";var ts=class extends Ue{fromBER(e,t,n){return t}toBER(e){return ut}};ts.override="EndOfContentValueBlock";var uf,rs=class extends Be{constructor(e={}){super(e,ts),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};uf=rs;T.EndOfContent=uf;rs.NAME=Hn;var ff,nr=class extends Be{constructor(e={}){super(e,Ue),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}`}};ff=nr;T.Null=ff;nr.NAME="NULL";var ns=class extends Ut(Ue){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=z.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=z.BufferSourceConverter.toUint8Array(e);return 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,nc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ns.NAME="BooleanValueBlock";var hf,os=class extends Be{constructor(e={}){super(e,ns),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}`}};hf=os;T.Boolean=hf;os.NAME="BOOLEAN";var ss=class extends Ut(wt){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=wt.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===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==of)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?wt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ss.NAME="OctetStringValueBlock";var df,Dt=class r extends Be{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=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=Ls(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?rr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return z.BufferSourceConverter.concat(e)}};df=Dt;T.OctetString=df;Dt.NAME=of;var is=class extends Ut(wt){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=wt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==sf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=z.BufferSourceConverter.toUint8Array(e);if(!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=Ls(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 wt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ut;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}}};is.NAME="BitStringValueBlock";var pf,nn=class extends Be{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},is),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let 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)}`}}};pf=nn;T.BitString=pf;nn.NAME=sf;var mf;function Gg(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=Wo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Wo(t,s)),s}function nf(r){if(r>=Vn.length)for(let e=Vn.length;e<=r;e++){let t=new Uint8Array([0]),n=Vn[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=Wo(t,n)),Vn.push(n)}return Vn[r]}function Yg(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 $n=class extends Ut(Ue){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=nc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(ef(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=Yg(nf(n),t),i="-";break;default:t=Gg(t,nf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=rf.charAt(t[c]));return a===!1&&(i+=rf.charAt(0)),i}};mf=$n;$n.NAME="IntegerValueBlock";Object.defineProperty(mf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var gf,ge=class r extends Be{constructor(e={}){super(e,$n),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return jo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){jo();let t=BigInt(e),n=new Kn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${z.Convert.ToHex(a)}`)+t,f=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};gf=ge;T.Integer=gf;ge.NAME="INTEGER";var yf,as=class extends ge{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};yf=as;T.Enumerated=yf;as.NAME="ENUMERATED";var qn=class extends Ut(Ue){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=z.BufferSourceConverter.toUint8Array(e);if(!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=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){jo();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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ut;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=z.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};qn.NAME="sidBlock";var cs=class extends Ue{constructor({value:e=on,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new qn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ut;t.push(o)}return oc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new qn;if(o>Number.MAX_SAFE_INTEGER){jo();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}};cs.NAME="ObjectIdentifierValueBlock";var wf,lt=class extends Be{constructor(e={}){super(e,cs),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()}}};wf=lt;T.ObjectIdentifier=wf;lt.NAME="OBJECT IDENTIFIER";var zn=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=z.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=Ar(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=tr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ut;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=z.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};zn.NAME="relativeSidBlock";var ls=class extends Ue{constructor({value:e=on,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new zn;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,ut;n.push(s)}return oc(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 zn;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}};ls.NAME="RelativeObjectIdentifierValueBlock";var bf,us=class extends Be{constructor(e={}){super(e,ls),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()}}};bf=us;T.RelativeObjectIdentifier=bf;us.NAME="RelativeObjectIdentifier";var Ef,_e=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Ef=_e;T.Sequence=Ef;_e.NAME="SEQUENCE";var xf,fs=class extends rr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};xf=fs;T.Set=xf;fs.NAME="SET";var hs=class extends Ut(Ue){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=on}toJSON(){return{...super.toJSON(),value:this.value}}};hs.NAME="StringValueBlock";var ds=class extends hs{};ds.NAME="SimpleStringValueBlock";var $e=class extends Qo{constructor({...e}={}){super(e,ds)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};$e.NAME="SIMPLE STRING";var ps=class extends $e{fromBuffer(e){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=z.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ps.NAME="Utf8StringValueBlock";var vf,Pt=class extends ps{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};vf=Pt;T.Utf8String=vf;Pt.NAME="UTF8String";var ms=class extends $e{fromBuffer(e){this.valueBlock.value=z.Convert.ToUtf16String(e),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(e))}};ms.NAME="BmpStringValueBlock";var _f,gs=class extends ms{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};_f=gs;T.BmpString=_f;gs.NAME="BMPString";var ys=class extends $e{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=tr(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}};ys.NAME="UniversalStringValueBlock";var Af,ws=class extends ys{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Af=ws;T.UniversalString=Af;ws.NAME="UniversalString";var Sf,bs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Sf=bs;T.NumericString=Sf;bs.NAME="NumericString";var Rf,Es=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Rf=Es;T.PrintableString=Rf;Es.NAME="PrintableString";var If,xs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};If=xs;T.TeletexString=If;xs.NAME="TeletexString";var Bf,vs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Bf=vs;T.VideotexString=Bf;vs.NAME="VideotexString";var Tf,_s=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Tf=_s;T.IA5String=Tf;_s.NAME="IA5String";var Cf,As=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Cf=As;T.GraphicString=Cf;As.NAME="GraphicString";var kf,Gn=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};kf=Gn;T.VisibleString=kf;Gn.NAME="VisibleString";var Nf,Ss=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Nf=Ss;T.GeneralString=Nf;Ss.NAME="GeneralString";var Lf,Rs=class extends $e{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Lf=Rs;T.CharacterString=Lf;Rs.NAME="CharacterString";var Df,Yn=class extends Gn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=ze(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ze(this.month,2),t[2]=ze(this.day,2),t[3]=ze(this.hour,2),t[4]=ze(this.minute,2),t[5]=ze(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Df=Yn;T.UTCTime=Df;Yn.NAME="UTCTime";var Pf,Is=class extends Yn{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(ze(this.year,4)),t.push(ze(this.month,2)),t.push(ze(this.day,2)),t.push(ze(this.hour,2)),t.push(ze(this.minute,2)),t.push(ze(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ze(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Pf=Is;T.GeneralizedTime=Pf;Is.NAME="GeneralizedTime";var Of,Bs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Of=Bs;T.DATE=Of;Bs.NAME="DATE";var Uf,Ts=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Uf=Ts;T.TimeOfDay=Uf;Ts.NAME="TimeOfDay";var Mf,Cs=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Mf=Cs;T.DateTime=Mf;Cs.NAME="DateTime";var Ff,ks=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Ff=ks;T.Duration=Ff;ks.NAME="Duration";var Vf,Ns=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Vf=Ns;T.TIME=Vf;Ns.NAME="TIME";function jg(r){let{result:e}=sn(r),t=e.valueBlock.value;return{n:F(bt(t[1].toBigInt()),"base64url"),e:F(bt(t[2].toBigInt()),"base64url"),d:F(bt(t[3].toBigInt()),"base64url"),p:F(bt(t[4].toBigInt()),"base64url"),q:F(bt(t[5].toBigInt()),"base64url"),dp:F(bt(t[6].toBigInt()),"base64url"),dq:F(bt(t[7].toBigInt()),"base64url"),qi:F(bt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Xg(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 ge({value:0}),ge.fromBigInt(Et(L(r.n,"base64url"))),ge.fromBigInt(Et(L(r.e,"base64url"))),ge.fromBigInt(Et(L(r.d,"base64url"))),ge.fromBigInt(Et(L(r.p,"base64url"))),ge.fromBigInt(Et(L(r.q,"base64url"))),ge.fromBigInt(Et(L(r.dp,"base64url"))),ge.fromBigInt(Et(L(r.dq,"base64url"))),ge.fromBigInt(Et(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Zg(r){let{result:e}=sn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:F(bt(t[0].toBigInt()),"base64url"),e:F(bt(t[1].toBigInt()),"base64url")}}function Qg(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 lt({value:"1.2.840.113549.1.1.1"}),new nr]}),new nn({valueHex:new _e({value:[ge.fromBigInt(Et(L(r.n,"base64url"))),ge.fromBigInt(Et(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function bt(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 Et(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 Jg=16,ic=32,ac=1e4;async function e0(r,e){let t=Fe.get(),o=new _e({value:[new ge({value:0}),new _e({value:[new lt({value:"1.2.840.113549.1.1.1"}),new nr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=yt(Jg),a=await tc(Ln,e,i,{c:ac,dkLen:ic}),c=yt(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 ge({value:ac}),new ge({value:ic}),new _e({value:[new lt({value:"1.2.840.113549.2.11"}),new nr]})]}),p=new _e({value:[new lt({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new lt({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new lt({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 t0(r,e){let t=Fe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=r0(s),l=await tc(Ln,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Wn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=sn(h);n=Kf(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}=sn(o);n=Kf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return cc(n)}function r0(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=Wn(s.valueBlock.value[0].getValue()),a=ac,c=ic;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=Wn(u.valueBlock.value[1].getValue());return{cipherText:Wn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Kf(r){return Wn(r.valueBlock.value[2].getValue())}function Wn(r){return new Uint8Array(r,0,r.byteLength)}async function Hf(r){let e=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await zf(e);return{privateKey:t[0],publicKey:t[1]}}async function lc(r){let t=[await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await n0(r)],n=await zf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function $f(r,e){let t=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function qf(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function zf(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)])}async function n0(r){return Fe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ds(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 Xn=8192,jn=class{_key;constructor(e){this._key=e}verify(e,t){return qf(this._key,t,e)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return mt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},an=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yt(16)}sign(e){return $f(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 or.jwkToPkcs1(this._key)}get bytes(){return gt.encode({Type:oe.RSA,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(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 or.exportToPem(this,e);if(t==="libp2p-key")return Jr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function cc(r){let e=or.pkcs1ToJwk(r);if(Ds(e)>Xn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await lc(e);return new an(t.privateKey,t.publicKey)}function s0(r){let e=or.pkixToJwk(r);if(Ds(e)>Xn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new jn(e)}async function i0(r){if(Ds(r)>Xn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await lc(r);return new an(e.privateKey,e.publicKey)}async function a0(r){if(r>Xn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Hf(r);return new an(e.privateKey,e.publicKey)}var mc={};ve(mc,{Secp256k1PrivateKey:()=>Qn,Secp256k1PublicKey:()=>Zn,generateKeyPair:()=>E0,unmarshalSecp256k1PrivateKey:()=>w0,unmarshalSecp256k1PublicKey:()=>b0});var c0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),fc=class extends jr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}get(){let{A:e,B:t,C:n,D: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)ir[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=ir[l-15],h=ir[l-2],d=st(p,7)^st(p,18)^p>>>3,m=st(h,17)^st(h,19)^h>>>10;ir[l]=m+ir[l-7]+d+ir[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=st(a,6)^st(a,11)^st(a,25),h=f+p+_u(a,c,u)+c0[l]+ir[l]|0,m=(st(n,2)^st(n,13)^st(n,22))+Au(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(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Gf=No(()=>new fc);function l0(r){let e=Pn(r);pt(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:u0,hexToBytes:f0}=Po,Sr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Sr;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:u0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Sr,t=typeof r=="string"?f0(r):r;Xr(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}=Sr._parseInt(t.subarray(2)),{d:i,l:a}=Sr._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}`}},Mt=BigInt(0),rt=BigInt(1),I1=BigInt(2),Yf=BigInt(3),B1=BigInt(4);function h0(r){let e=l0(r),{Fp:t}=e,n=e.toBytes||((d,m,y)=>{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),y=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function s(d){let{a:m,b:y}=e,g=t.sqr(d),w=t.mul(g,d);return t.add(t.add(w,t.mul(d,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Mt<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:g,n:w}=e;if(m&&typeof d!="bigint"){if(Zt(d)&&(d=Bt(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(y*2,"0")}let b;try{b=typeof d=="bigint"?d:Tt(le("private key",d,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=Q(b,w)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,g){if(this.px=m,this.py=y,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(m){let{x:y,y:g}=m||{};if(!m||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let w=b=>t.eql(b,t.ZERO);return w(y)&&w(g)?l.ZERO:new l(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(g=>g.pz));return m.map((g,w)=>g.toAffine(y[w])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(o(le("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),w=s(m);if(!t.eql(g,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.eql(t.mul(y,v),t.mul(b,w)),_=t.eql(t.mul(g,v),t.mul(x,w));return S&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,g=t.mul(y,Yf),{px:w,py:b,pz:x}=this,v=t.ZERO,S=t.ZERO,_=t.ZERO,R=t.mul(w,w),$=t.mul(b,b),q=t.mul(x,x),U=t.mul(w,b);return U=t.add(U,U),_=t.mul(w,x),_=t.add(_,_),v=t.mul(m,_),S=t.mul(g,q),S=t.add(v,S),v=t.sub($,S),S=t.add($,S),S=t.mul(v,S),v=t.mul(U,v),_=t.mul(g,_),q=t.mul(m,q),U=t.sub(R,q),U=t.mul(m,U),U=t.add(U,_),_=t.add(R,R),R=t.add(_,R),R=t.add(R,q),R=t.mul(R,U),S=t.add(S,R),q=t.mul(b,x),q=t.add(q,q),R=t.mul(q,U),v=t.sub(v,R),_=t.mul(q,$),_=t.add(_,_),_=t.add(_,_),new l(v,S,_)}add(m){f(m);let{px:y,py:g,pz:w}=this,{px:b,py:x,pz:v}=m,S=t.ZERO,_=t.ZERO,R=t.ZERO,$=e.a,q=t.mul(e.b,Yf),U=t.mul(y,b),ee=t.mul(g,x),D=t.mul(w,v),Qe=t.add(y,g),I=t.add(b,x);Qe=t.mul(Qe,I),I=t.add(U,ee),Qe=t.sub(Qe,I),I=t.add(y,w);let N=t.add(b,v);return I=t.mul(I,N),N=t.add(U,D),I=t.sub(I,N),N=t.add(g,w),S=t.add(x,v),N=t.mul(N,S),S=t.add(ee,D),N=t.sub(N,S),R=t.mul($,I),S=t.mul(q,D),R=t.add(S,R),S=t.sub(ee,R),R=t.add(ee,R),_=t.mul(S,R),ee=t.add(U,U),ee=t.add(ee,U),D=t.mul($,D),I=t.mul(q,I),ee=t.add(ee,D),D=t.sub(U,D),D=t.mul($,D),I=t.add(I,D),U=t.mul(ee,I),_=t.add(_,U),U=t.mul(N,I),S=t.mul(Qe,S),S=t.sub(S,U),U=t.mul(Qe,ee),R=t.mul(N,R),R=t.add(R,U),new l(S,_,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let g=t.invertBatch(y.map(w=>w.pz));return y.map((w,b)=>w.toAffine(g[b])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Mt)return y;if(a(m),m===rt)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:w,k1:b,k2neg:x,k2:v}=g.splitScalar(m),S=y,_=y,R=this;for(;b>Mt||v>Mt;)b&rt&&(S=S.add(R)),v&rt&&(_=_.add(R)),R=R.double(),b>>=rt,v>>=rt;return w&&(S=S.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),S.add(_)}multiply(m){a(m);let y=m,g,w,{endo:b}=e;if(b){let{k1neg:x,k1:v,k2neg:S,k2:_}=b.splitScalar(y),{p:R,f:$}=this.wNAF(v),{p:q,f:U}=this.wNAF(_);R=h.constTimeNegate(x,R),q=h.constTimeNegate(S,q),q=new l(t.mul(q.px,b.beta),q.py,q.pz),g=R.add(q),w=$.add(U)}else{let{p:x,f:v}=this.wNAF(y);g=x,w=v}return l.normalizeZ([g,w])[0]}multiplyAndAddUnsafe(m,y,g){let w=l.BASE,b=(v,S)=>S===Mt||S===rt||!v.equals(w)?v.multiplyUnsafe(S):v.multiply(S),x=b(this,y).add(b(m,g));return x.is0()?void 0:x}toAffine(m){let{px:y,py:g,pz:w}=this,b=this.is0();m==null&&(m=b?t.ONE:t.inv(w));let x=t.mul(y,m),v=t.mul(g,m),S=t.mul(w,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===rt)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===rt?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Bt(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=Mo(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function d0(r){let e=Pn(r);return pt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Wf(r){let e=d0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Mt<I&&I<t.ORDER}function a(I){return Q(I,n)}function c(I){return Oo(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:p}=h0({...e,toBytes(I,N,V){let B=N.toAffine(),A=t.toBytes(B.x),k=Ct;return V?k(Uint8Array.from([N.hasEvenY()?2:3]),A):k(Uint8Array.from([4]),A,t.toBytes(B.y))},fromBytes(I){let N=I.length,V=I[0],B=I.subarray(1);if(N===o&&(V===2||V===3)){let A=Tt(B);if(!i(A))throw new Error("Point is not on curve");let k=l(A),P;try{P=t.sqrt(k)}catch(H){let W=H instanceof Error?": "+H.message:"";throw new Error("Point is not on curve"+W)}let O=(P&rt)===rt;return(V&1)===1!==O&&(P=t.neg(P)),{x:A,y:P}}else if(N===s&&V===4){let A=t.fromBytes(B.subarray(0,t.BYTES)),k=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:A,y:k}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>Bt(Jt(I,e.nByteLength));function d(I){let N=n>>rt;return I>N}function m(I){return d(I)?a(-I):I}let y=(I,N,V)=>Tt(I.slice(N,V));class g{constructor(N,V,B){this.r=N,this.s=V,this.recovery=B,this.assertValidity()}static fromCompact(N){let V=e.nByteLength;return N=le("compactSignature",N,V*2),new g(y(N,0,V),y(N,V,2*V))}static fromDER(N){let{r:V,s:B}=Sr.toSig(le("DER",N));return new g(V,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:V,s:B,recovery:A}=this,k=_(le("msgHash",N));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let P=A===2||A===3?V+e.n:V;if(P>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let O=A&1?"03":"02",K=u.fromHex(O+h(P)),H=c(P),W=a(-k*H),G=a(B*H),Y=u.BASE.multiplyAndAddUnsafe(K,W,G);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return yr(this.toDERHex())}toDERHex(){return Sr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=ka(e.n);return Du(e.randomBytes(I),e.n)},precompute(I=8,N=u.BASE){return N._setWindowSize(I),N.multiply(BigInt(3)),N}};function b(I,N=!0){return u.fromPrivateKey(I).toRawBytes(N)}function x(I){let N=Zt(I),V=typeof I=="string",B=(N||V)&&I.length;return N?B===o||B===s:V?B===2*o||B===2*s:I instanceof u}function v(I,N,V=!0){if(x(I))throw new Error("first arg must be private key");if(!x(N))throw new Error("second arg must be public key");return u.fromHex(N).multiply(f(I)).toRawBytes(V)}let S=e.bits2int||function(I){let N=Tt(I),V=I.length*8-e.nBitLength;return V>0?N>>BigInt(V):N},_=e.bits2int_modN||function(I){return a(S(I))},R=Dn(e.nBitLength);function $(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Mt<=I&&I<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Jt(I,e.nByteLength)}function q(I,N,V=U){if(["recovered","canonical"].some(ae=>ae in V))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:A}=e,{lowS:k,prehash:P,extraEntropy:O}=V;k==null&&(k=!0),I=le("msgHash",I),P&&(I=le("prehashed msgHash",B(I)));let K=_(I),H=f(N),W=[$(H),$(K)];if(O!=null&&O!==!1){let ae=O===!0?A(t.BYTES):O;W.push(le("extraEntropy",ae))}let G=Ct(...W),Y=K;function pe(ae){let Ae=S(ae);if(!p(Ae))return;let Se=c(Ae),ye=u.BASE.multiply(Ae).toAffine(),Ne=a(ye.x);if(Ne===Mt)return;let vt=a(Se*a(Y+Ne*H));if(vt===Mt)return;let pr=(ye.x===Ne?0:2)|Number(ye.y&rt),Bn=vt;return k&&d(vt)&&(Bn=m(vt),pr^=1),new g(Ne,Bn,pr)}return{seed:G,k2sig:pe}}let U={lowS:e.lowS,prehash:!1},ee={lowS:e.lowS,prehash:!1};function D(I,N,V=U){let{seed:B,k2sig:A}=q(I,N,V),k=e;return Ia(k.hash.outputLen,k.nByteLength,k.hmac)(B,A)}u.BASE._setWindowSize(8);function Qe(I,N,V,B=ee){let A=I;if(N=le("msgHash",N),V=le("publicKey",V),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:k,prehash:P}=B,O,K;try{if(typeof A=="string"||Zt(A))try{O=g.fromDER(A)}catch(ye){if(!(ye instanceof Sr.Err))throw ye;O=g.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:ye,s:Ne}=A;O=new g(ye,Ne)}else throw new Error("PARSE");K=u.fromHex(V)}catch(ye){if(ye.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(k&&O.hasHighS())return!1;P&&(N=e.hash(N));let{r:H,s:W}=O,G=_(N),Y=c(W),pe=a(G*Y),ae=a(H*Y),Ae=u.BASE.multiplyAndAddUnsafe(K,pe,ae)?.toAffine();return Ae?a(Ae.x)===H:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:D,verify:Qe,ProjectivePoint:u,Signature:g,utils:w}}function p0(r){return{hash:r,hmac:(e,...t)=>Fn(r,e,va(...t)),randomBytes:Wr}}function jf(r,e){let t=n=>Wf({...r,...p0(n)});return Object.freeze({...t(e),create:t})}var Qf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),m0=BigInt(1),hc=BigInt(2),Zf=(r,e)=>(r+e/hc)/e;function g0(r){let e=Qf,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ne(f,t,e)*f%e,p=ne(l,t,e)*f%e,h=ne(p,hc,e)*u%e,d=ne(h,o,e)*h%e,m=ne(d,s,e)*d%e,y=ne(m,a,e)*m%e,g=ne(y,c,e)*y%e,w=ne(g,a,e)*m%e,b=ne(w,t,e)*f%e,x=ne(b,i,e)*d%e,v=ne(x,n,e)*u%e,S=ne(v,hc,e);if(!dc.eql(dc.sqr(S),r))throw new Error("Cannot find square root");return S}var dc=Uo(Qf,void 0,void 0,{sqrt:g0}),ft=jf({a:BigInt(0),b:BigInt(7),Fp:dc,n:Xf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Xf,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-m0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Zf(s*r,e),c=Zf(-n*r,e),u=Q(r-a*t-c*o,e),f=Q(-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}}}},Gf),U1=BigInt(0);var M1=ft.ProjectivePoint;function Jf(){return ft.utils.randomPrivateKey()}function eh(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(et(t))return t.then(({digest:n})=>ft.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return ft.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function th(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(et(n))return n.then(({digest:o})=>ft.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return ft.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function rh(r){return ft.ProjectivePoint.fromHex(r).toRawBytes(!0)}function nh(r){try{ft.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function pc(r){try{ft.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function oh(r){try{return ft.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Zn=class{_key;constructor(e){pc(e),this._key=e}verify(e,t){return th(this._key,t,e)}marshal(){return rh(this._key)}get bytes(){return mt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}},Qn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??oh(e),nh(this._key),pc(this._publicKey)}sign(e){return eh(this._key,e)}get public(){return new Zn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:oe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return te(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return et(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 Jr(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function w0(r){return new Qn(r)}function b0(r){return new Zn(r)}async function E0(){let r=Jf();return new Qn(r)}var ar={rsa:uc,ed25519:ec,secp256k1:mc};function gc(r){let e=Object.keys(ar).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function yc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ar[r];throw gc(r)}async function sh(r,e){return yc(r).generateKeyPair(e??2048)}function Jn(r){let e=mt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return ar.rsa.unmarshalRsaPublicKey(t);case oe.Ed25519:return ar.ed25519.unmarshalEd25519PublicKey(t);case oe.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw gc(e.Type??"unknown")}}function ih(r,e){return e=(e??"rsa").toLowerCase(),yc(e),r.bytes}async function eo(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case oe.RSA:return ar.rsa.unmarshalRsaPrivateKey(t);case oe.Ed25519:return ar.ed25519.unmarshalEd25519PrivateKey(t);case oe.Secp256k1:return ar.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw gc(e.Type??"RSA")}}function ah(r,e){return e=(e??"rsa").toLowerCase(),yc(e),r.bytes}function x0(r,e){try{if(typeof r=="string"&&r.length>0)return v0(r);if(typeof r=="number"&&isFinite(r))return e?.long?A0(r):_0(r);throw new Error("Value is not a string or number.")}catch(t){let n=S0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function v0(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 Os=x0;function _0(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 A0(r){let e=Math.abs(r);return e>=864e5?Ps(r,e,864e5,"day"):e>=36e5?Ps(r,e,36e5,"hour"):e>=6e4?Ps(r,e,6e4,"minute"):e>=1e3?Ps(r,e,1e3,"second"):`${r} ms`}function Ps(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function S0(r){return typeof r=="object"&&r!==null&&"message"in r}function wc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Os,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(...y){if(!m.enabled)return;let g=m,w=Number(new Date),b=w-(l||w);g.diff=b,g.prev=l,g.curr=w,l=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(S,_)=>{if(S==="%%")return"%";x++;let R=t.formatters[_];if(typeof R=="function"){let $=y[x];S=R.call(g,$),y.splice(x,1),x--}return S}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}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:y=>{p=y}}),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 Us=N0(),R0=["#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 I0(){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 B0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Os(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 T0=console.debug??console.log??(()=>{});function C0(r){try{r?Us?.setItem("debug",r):Us?.removeItem("debug")}catch{}}function k0(){let r;try{r=Us?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function N0(){try{return localStorage}catch{}}function L0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var ch=wc({formatArgs:B0,save:C0,load:k0,useColors:I0,setupFormatters:L0,colors:R0,storage:Us,log:T0});var je=ch;je.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);je.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);je.formatters.m=r=>r==null?"undefined":kn.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 D0(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 Ms(){return{forComponent(r){return P0(r)}}}function P0(r){let e=D0(`${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 uh=Symbol.for("nodejs.util.inspect.custom"),lh=Object.values(Yt).map(r=>r.decoder).reduce((r,e)=>r.or(e),Yt.identity.decoder),fh=114,xc=36,vc=37,to=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()})`}[Ao]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Je.createV1(fh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return te(this.multihash.bytes,e);if(typeof e=="string")return be(e).equals(this);if(e?.multihash?.bytes!=null)return te(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[uh](){return`PeerId(${this.toString()})`}},Rr=class extends to{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ir=class extends to{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends to{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},bc=2336,Ec=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Rt.digest(L(this.url))}[uh](){return`PeerId(${this.url})`}[Ao]=!0;toString(){return this.toCID().toString()}toCID(){return Je.createV1(bc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function hh(r){if(r.type==="RSA")return new Rr(r);if(r.type==="Ed25519")return new Ir(r);if(r.type==="secp256k1")return new Br(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function be(r,e){if(e=e??lh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ie.decode(`z${r}`));return r.startsWith("12D")?new Ir({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Rr({multihash:t})}return cn(lh.decode(r))}function cn(r){try{let e=mr(r);if(e.code===Rt.code){if(e.digest.length===xc)return new Ir({multihash:e});if(e.digest.length===vc)return new Br({multihash:e})}if(e.code===Re.code)return new Rr({multihash:e})}catch{return O0(Je.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function O0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==fh&&r.code!==bc)throw new Error("Supplied PeerID CID is invalid");if(r.code===bc){let t=F(r.multihash.digest);return new Ec(new URL(t))}let e=r.multihash;if(e.code===Re.code)return new Rr({multihash:r.multihash});if(e.code===Rt.code){if(e.digest.length===xc)return new Ir({multihash:r.multihash});if(e.digest.length===vc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ln(r,e){return r.length===xc?new Ir({multihash:dt(Rt.code,r),privateKey:e}):r.length===vc?new Br({multihash:dt(Rt.code,r),privateKey:e}):new Rr({multihash:await Re.digest(r),publicKey:r,privateKey:e})}function un(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 un(this.map.entries(),e=>[be(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,be(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 un(this.map.keys(),e=>be(e))}values(){return this.map.values()}get size(){return this.map.size}};var Ft=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 un(this.set.entries(),e=>{let t=be(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=be(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return un(this.set.values(),e=>be(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 yh=Symbol.for("@achingbrain/uint8arraylist");function gh(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 Vs(r){return!!r?.[yh]}var Ee=class r{bufs;length;[yh]=!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(Vs(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(Vs(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=gh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=gh(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(Vs(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ie(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ie(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Vs(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=Le(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=ot(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=ot(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=ot(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=Le(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=ot(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=ot(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=ot(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=ot(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=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var _c=64,ht=class{fp;h;seed;constructor(e,t,n,o=2){if(o>_c)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ot(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?te(this.fp,e.fp):!1}};function Tr(r,e){return Math.floor(Math.random()*(e-r))+r}var Cr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ht))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ht))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 ht))throw new TypeError("Invalid Fingerprint");let t=Tr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ht))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ac={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},wh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},bh=new globalThis.TextEncoder;function U0(r,e){let t=Ac[e],n=wh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function M0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ac[e],o=wh[e],s=r;for(;s.length>0;){let i=bh.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 Sc(r,{size:e=32,utf8Buffer:t}={}){if(!Ac[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 M0(r,e,t);r=bh.encode(r)}return U0(r,e)}var F0=$t(mh(),1);var no={hash:r=>Number(Sc(r,{size:32})),hashV:(r,e)=>V0(no.hash(r,e))};function V0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var K0=500,oo=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??no,this.seed=e.seed??Tr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new ht(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 Cr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Cr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Tr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Cr(this.bucketSize));for(let a=0;a<K0;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 Cr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new ht(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 ht(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}},H0={1:.5,2:.84,4:.95,8:.98};function $0(r=.001){return r>.002?2:r>1e-5?4:8}function Eh(r,e=.001){let t=$0(e),n=H0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),_c);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Ks=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??no,this.seed=e.seed??Tr(0,Math.pow(2,10)),this.filterSeries=[new oo({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 oo({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 Rc(r,e=.001,t){return new Ks({...Eh(r,e),...t??{}})}var xh=async()=>{let r=await sh("Ed25519"),e=await q0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function q0(r){return ln(ih(r.public),ah(r))}var vh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var so;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(so||(so={}));var fn=class r{static createFromProtobuf=async e=>{let t=so.decode(e),n=await ln(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=_h(n,o,s),c=await(await eo(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",vh.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=so.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return te(this.marshal(),e.marshal())}async validate(e){let t=_h(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Jn(this.peerId.publicKey).verify(t.subarray(),this.signature)}},_h=(r,e,t)=>{let n=L(r),o=Pe(n.byteLength),s=Pe(e.length),i=Pe(t.length);return new Ee(o,n,s,e,i,t)};function Ah(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 Hs=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 Sh=45,z0=15,hn=new Hs;function Ic(r){if(!(r.length>z0))return hn.new(r).parseWith(()=>hn.readIPv4Addr())}function Bc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Sh))return hn.new(r).parseWith(()=>hn.readIPv6Addr())}function $s(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Sh))return hn.new(r).parseWith(()=>hn.readIPAddr())}var U_=parseInt("0xFFFF",16),M_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function dn(r){return!!Ic(r)}function pn(r){return!!Bc(r)}function qs(r){return!!$s(r)}var Bh=dn,X0=pn,Tc=function(r){let e=0;if(r=r.toString().trim(),Bh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(X0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Bh(t[n]),i;s&&(i=Tc(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")},Th=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var mn={},Cc={},Q0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Q0.forEach(r=>{let e=J0(...r);Cc[e.code]=e,mn[e.name]=e});function J0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(Cc[r]!=null)return Cc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(mn[r]!=null)return mn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var xA=Z("ip4"),vA=Z("ip6"),_A=Z("ipcidr");function Dc(r,e){switch(Z(r).code){case 4:case 41:return ty(e);case 42:return Lc(e);case 6:case 273:case 33:case 132:return Nh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Lc(e);case 421:return sy(e);case 444:return kh(e);case 445:return kh(e);case 466:return oy(e);case 481:return globalThis.encodeURIComponent(Lc(e));default:return F(e,"base16")}}function Pc(r,e){switch(Z(r).code){case 4:return Ch(e);case 41:return Ch(e);case 42:return Nc(e);case 6:case 273:case 33:case 132:return Oc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Nc(e);case 421:return ry(e);case 444:return iy(e);case 445:return ay(e);case 466:return ny(e);case 481:return Nc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var kc=Object.values(Yt).map(r=>r.decoder),ey=function(){let r=kc[0].or(kc[1]);return kc.slice(2).forEach(e=>r=r.or(e)),r}();function Ch(r){if(!qs(r))throw new Error("invalid ip address");return Tc(r)}function ty(r){let e=Th(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!qs(e))throw new Error("invalid ip address");return e}function Oc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Nh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Nc(r){let e=L(r),t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function Lc(r){let e=at(r);if(r=r.slice(me(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function ry(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ie.decode(`z${r}`)).bytes:e=Je.parse(r).multihash.bytes;let t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function ny(r){let e=ey.decode(r),t=Uint8Array.from(Pe(e.length));return Ie([t,e],t.length+e.length)}function oy(r){let e=at(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function sy(r){let e=at(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function iy(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=Ge.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=Oc(n);return Ie([t,o],t.length+o.length)}function ay(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.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=Oc(n);return Ie([t,o],t.length+o.length)}function kh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Nh(t);return`${n}:${o}`}function Lh(r){r=Uc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Z(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Ph("invalid address: "+r);if(a.path===!0){n=Uc(o.slice(s).join("/")),e.push([a.code,Pc(a.code,n)]),t.push([a.code,n]);break}let c=Pc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Dc(a.code,c)])}return{string:Dh(t),bytes:Fc(e),tuples:e,stringTuples:t,path:n}}function Mc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=at(r,o),i=me(s),a=Z(s),c=cy(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 Ph("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=Dc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Dh(t),tuples:e,stringTuples:t,path:n}}function Dh(r){let e=[];return r.map(t=>{let n=Z(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Uc(e.join("/"))}function Fc(r){return Ie(r.map(e=>{let t=Z(e[0]),n=Uint8Array.from(Pe(t.code));return e.length>1&&e[1]!=null&&(n=Ie([n,e[1]])),n}))}function cy(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=at(e instanceof Uint8Array?e:Uint8Array.from(e));return t+me(t)}}function Uc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Ph(r){return new Error("Error parsing address: "+r)}var ly=Symbol.for("nodejs.util.inspect.custom"),Vc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),uy=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],zs=class r{bytes;#e;#t;#s;#a;[Vc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Mc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Lh(e)}else if(cr(e))t=Mc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),uy.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=Z(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=Z(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({},Z(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Z(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Fc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===mn.p2p.code&&e.push([n,o]),n===mn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?F(ie.decode(`z${n}`),"base58btc"):F(Je.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return te(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=gn.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=>se(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[ly](){return`Multiaddr(${this.#e})`}};var gn=new Map;function cr(r){return!!r?.[Vc]}function se(r){return new zs(r)}var Oh="libp2p-peer-record",Uh=Uint8Array.from([3,1]);var io;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=He((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Ke(s,n.codec()),n.decode=s=>Ve(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=He((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Ke(n,r.codec()),r.decode=n=>Ve(n,r.codec())})(io||(io={}));var kr=class r{static createFromProtobuf=e=>{let t=io.decode(e),n=cn(t.peerId),o=(t.addresses??[]).map(i=>se(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Oh;static CODEC=Uh;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=io.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||!Ah(this.multiaddrs,e.multiaddrs))}};function fy(r){return r[Symbol.asyncIterator]!=null}function hy(r){if(fy(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 ao=hy;var Hc=$t(Fh(),1);var lo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},$c=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Vh=r=>globalThis.DOMException===void 0?new $c(r):new DOMException(r),Kh=r=>{let e=r.reason===void 0?Vh("This operation was aborted."):r.reason;return e instanceof Error?e:Vh(e)};function uo(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(Kh(p)),p.addEventListener("abort",()=>{f(Kh(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new lo;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 qc(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 fo=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=qc(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 lr=class extends Hc.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:fo,...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=uo(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 lo&&!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 ur={},yn=r=>{r.addEventListener("message",e=>{yn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{yn.dispatchEvent("message",r,e)})};yn.addEventListener=(r,e)=>{ur[r]==null&&(ur[r]=[]),ur[r].push(e)};yn.removeEventListener=(r,e)=>{ur[r]!=null&&(ur[r]=ur[r].filter(t=>t===e))};yn.dispatchEvent=function(r,e,t){ur[r]!=null&&ur[r].forEach(n=>n(e,t))};var zc=yn;var Gc="lock:worker:request-read",Yc="lock:worker:release-read",Wc="lock:master:grant-read",jc="lock:worker:request-write",Xc="lock:worker:release-write",Zc="lock:master:grant-write";var Hh=(r=21)=>Math.random().toString().substring(2);var $h=(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)})}}}))},qh=(r,e,t,n)=>async()=>{let o=Hh();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)})},my={singleProcess:!1},zh=r=>{if(r=Object.assign({},my,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return zc.addEventListener("message",$h(t,"requestReadLock",Gc,Yc,Wc)),zc.addEventListener("message",$h(t,"requestWriteLock",jc,Xc,Zc)),t}return{isWorker:!0,readLock:t=>qh(t,Gc,Wc,Yc),writeLock:t=>qh(t,jc,Zc,Xc)}};var Nr={},fr;async function Qc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>uo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var gy=(r,e)=>{if(fr.isWorker===!0)return{readLock:fr.readLock(r,e),writeLock:fr.writeLock(r,e)};let t=new lr({concurrency:1}),n;return{async readLock(){if(n!=null)return Qc(n,e);n=new lr({concurrency:e.concurrency,autoStart:!1});let o=n,s=Qc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Qc(t,e)}}},yy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Jc(r){let e=Object.assign({},yy,r);return fr==null&&(fr=zh(e),fr.isWorker!==!0&&(fr.addEventListener("requestReadLock",t=>{Nr[t.data.name]!=null&&Nr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),fr.addEventListener("requestWriteLock",async t=>{Nr[t.data.name]!=null&&Nr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Nr[e.name]==null&&(Nr[e.name]=gy(e.name,e)),Nr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var wn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=He((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=He((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ws.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=Ws.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Ke(i,o.codec()),o.decode=i=>Ve(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=He((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ys.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(Ys.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Ke(o,r.codec()),r.decode=o=>Ve(o,r.codec())})(wn||(wn={}));var Ys;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(Ys||(Ys={}));var Ws;(function(r){let e;r.codec=()=>(e==null&&(e=He((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Ke(t,r.codec()),r.decode=t=>Ve(t,r.codec())})(Ws||(Ws={}));function bn(r,e){let t=wn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=hh({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:se(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Vt="/",Gh=new TextEncoder().encode(Vt),js=Gh[0],Lr=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]!==js)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(Vt))}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=Gh),this._buf[0]!==js){let e=new Uint8Array(this._buf.byteLength+1);e.fill(js,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===js;)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(Vt).slice(1)}type(){return wy(this.baseNamespace())}name(){return by(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Vt)||(e+=Vt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Vt):new r(e.slice(0,-1).join(Vt))}child(e){return this.toString()===Vt?e:e.toString()===Vt?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(),...Ey(e.map(t=>t.namespaces()))])}};function wy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function by(r){let e=r.split(":");return e[e.length-1]}function Ey(r){return[].concat(...r)}var el="/peers/";function En(r){if(!So(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Lr(`${el}${e}`)}async function Yh(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=se(o.multiaddr)),!cr(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 Zs(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!te(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=Xs(l,{validate:Wh})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Xs(l,{validate:jh,map:Xh})}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=Xs([...a.entries()],{validate:Wh})}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=Xs([...p.entries()],{validate:jh,map:Xh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Yh(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 Xs(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 Wh(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 jh(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 Xh(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 Qs(r,e,t){let n=r.toString().split("/")[2],o=Ge.decode(n),s=cn(o),i=t.get(s);if(i!=null)return i;let a=bn(s,e);return t.set(s,a),a}function xy(r,e){return r==null?{}:{prefix:el,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Qs(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Qs(n.key,n.value,e),Qs(o.key,o.value,e)))}}var Js=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Jc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(En(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(En(e))}async load(e){let t=await this.datastore.get(En(e));return bn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Zs(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 Zs(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 Zs(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(xy(e??{},t))){let s=Qs(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(En(e)),n=bn(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=wn.encode(t);return n!=null&&te(s,n)?{peer:bn(e,s),previous:o,updated:!1}:(await this.datastore.put(En(e),s),{peer:bn(e,s),previous:o,updated:!0})}};var ei=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 Js(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 ao(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 fn.openAndCertify(e,kr.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=kr.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 fn.createFromProtobuf(s.peerRecordEnvelope),a=kr.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 vy(r){return r[Symbol.asyncIterator]!=null}function _y(r){if(vy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var tl=_y;function Ay(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 Zh=Ay;function Sy(r){return r[Symbol.asyncIterator]!=null}function Ry(r,e){let t=0;if(Sy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Zh(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 Dr=Ry;function Iy(r){return r[Symbol.asyncIterator]!=null}function By(r,e){return Iy(r)?async function*(){yield*(await ao(r)).sort(e)}():function*(){yield*ao(r).sort(e)}()}var rl=By;function Ty(r){return r[Symbol.asyncIterator]!=null}function Cy(r,e){return Ty(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 nl=Cy;var ti=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 tl(this.putMany(e,n)),e=[],await tl(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=Dr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>rl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Dr(n,()=>o++>=s)}return e.limit!=null&&(n=nl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Dr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Dr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>rl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Dr(n,()=>s++>=o)}return e.limit!=null&&(n=nl(n,e.limit)),n}};var ed=$t(ol(),1);function td(r){return r=r??new Error("Not Found"),(0,ed.default)(r,"ERR_NOT_FOUND")}var ri=class extends ti{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 td();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 Lr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Lr(e)}};function rd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Ly=r=>r;function sl(r,e){let t=r.getPeerId();return t!=null&&be(t).equals(e)&&(r=r.decapsulate(se(`/p2p/${e.toString()}`))),r}var ni=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??Ly,this._updatePeerStoreAddresses=rd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>se(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>se(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>se(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>se(e))}addObservedAddr(e){e=sl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=sl(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=sl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>se(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var il=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=Ms())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ql(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")}},Dy=["metrics","connectionProtector","dns"],Py=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function nd(r={}){let e=new il(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Py.includes(o)){let i=e.components[o];if(i==null&&!Dy.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 od(r){let e={};for(let t of Object.values(r.components))for(let n of Oy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Uy(t))if(e[n]!==!0)throw new E(`Service "${My(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 Oy(r){return Array.isArray(r?.[Qi])?r[Qi]:[]}function Uy(r){return Array.isArray(r?.[Ji])?r[Ji]:[]}function My(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var id=$t(sd(),1),Fy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Vy=Fy.map(r=>new id.Netmask(r));function al(r){for(let e of Vy)if(e.contains(r))return!0;return!1}function Ky(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Hy(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 al(o)}function $y(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function qy(r){let e=r.split(":"),t=e[e.length-1];return al(t)}function zy(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 oi(r){return dn(r)?al(r):Ky(r)?Hy(r):$y(r)?qy(r):pn(r)?zy(r):void 0}function ad(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!oi(`${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 Gy=r=>r.toString().split("/").slice(1),po=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),j=r=>({match:e=>po(t=>t===r).match(e),pattern:r}),ai=()=>({match:r=>po(e=>typeof e=="string").match(r),pattern:"{string}"}),ci=()=>({match:r=>po(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ce=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ie.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),si=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ga.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),xe=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),nt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),J=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function he(...r){function e(o){let s=Gy(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 ll=J(j("dns4"),ai()),ul=J(j("dns6"),ai()),fl=J(j("dnsaddr"),ai()),cd=J(j("dns"),ai()),WS=he(ll),jS=he(ul),XS=he(fl),ZS=he(nt(cd,fl,ll,ul)),ld=J(j("ip4"),po(dn)),ud=J(j("ip6"),po(pn)),fd=nt(ld,ud),xt=nt(fd,cd,ll,ul,fl),QS=he(xt),JS=he(ld),eR=he(ud),tR=he(fd),hl=J(xt,j("tcp"),ci()),mo=J(xt,j("udp"),ci()),rR=he(hl),nR=he(mo),dl=J(mo,j("quic")),li=J(mo,j("quic-v1")),Yy=nt(dl,li),oR=he(dl),sR=he(li),cl=nt(xt,hl,mo,dl,li),hd=nt(J(cl,j("ws"),xe(Ce()))),iR=he(hd),dd=nt(J(cl,j("wss"),xe(Ce())),J(cl,j("tls"),j("ws"),xe(Ce()))),aR=he(dd),pd=J(mo,j("webrtc-direct"),xe(si()),xe(si()),xe(Ce())),cR=he(pd),md=J(li,j("webtransport"),xe(si()),xe(si()),xe(Ce())),lR=he(md),ii=nt(hd,dd,J(hl,xe(Ce())),J(Yy,xe(Ce())),J(xt,xe(Ce())),pd,md,Ce()),uR=he(ii),Wy=J(ii,j("p2p-circuit"),Ce()),go=he(Wy),jy=nt(J(ii,j("p2p-circuit"),j("webrtc"),xe(Ce())),J(ii,j("webrtc"),xe(Ce())),j("webrtc")),fR=he(jy),Xy=nt(J(xt,j("tcp"),ci(),j("http"),xe(Ce())),J(xt,j("http"),xe(Ce()))),hR=he(Xy),Zy=nt(J(xt,j("tcp"),nt(J(j("443"),j("http")),J(ci(),j("https"))),xe(Ce())),J(xt,j("tls"),j("http"),xe(Ce())),J(xt,j("https"),xe(Ce()))),dR=he(Zy);function pl(r){try{let{address:e}=r.nodeAddress();return!!oi(e)}catch{return!0}}function Qy(r,e){let t=pl(r.multiaddr),n=pl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Jy(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function ew(r,e){let t=go.exactMatch(r.multiaddr),n=go.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function xn(r,e){let t=Qy(r,e);if(t!==0)return t;let n=ew(r,e);return n!==0?n:Jy(r,e)}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ui(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var ml=60;function fi(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??ml,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var tw=4;function gl(r,e={}){let t=new lr({concurrency:e.queryConcurrency??tw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ui(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new de("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=fi(await a.json());return o.onProgress?.(new de("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function gd(){return[gl("https://cloudflare-dns.com/dns-query"),gl("https://dns.google/resolve")]}var bd=$t(wd(),1);var yl=class{lru;constructor(e){this.lru=(0,bd.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 fi({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??ml)*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 Ed(r){return new yl(r)}var rw=1e3,hi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Ed(e.cacheSize??rw),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["."]=gd())}async query(e,t={}){let n=ui(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new de("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function xd(r={}){return new hi(r)}var nw=32,{code:ow}=Z("dnsaddr"),Pr=async function(e,t={}){let n=t.maxRecursiveDepth??nw;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===ow)??[],i=await(t?.dns??xd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=se(f);if(f.startsWith("/dnsaddr")){let p=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...p.map(h=>h.toString()))}else c.push(l.toString())}return c};var Cd=$t(Td(),1),mi=Cd.default;var Kt;(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"})(Kt||(Kt={}));var C;(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"})(C||(C={}));var uw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Pr},addressSorter:xn},transportManager:{faultTolerance:qt.FATAL_ALL}};async function kd(r){let e=mi(uw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Kt.ERR_PROTECTOR_REQUIRED,C.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await ln(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",C.ERR_INVALID_KEY);return e}var Nd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},fw=new WeakMap;function hw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Nd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Nd())},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}),fw.set(l,()=>{c(s),s=null,i()}),l}}var dw=hw(),Ld=dw;var gi=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 bl}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 Ld(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)}},bl=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 yi(r){if(So(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:be(t),r.forEach(n=>{if(!cr(n))throw new E("Invalid Multiaddr",C.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",C.ERR_INVALID_PARAMETERS)}else{let s=be(o);if(e?.equals(s)!==!0)throw new E("Multiaddrs must all have the same peer id or have no peer id",C.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 wi=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}},An=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new wi(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 wi(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 El=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function bi(r={}){return pw(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 pw(r,e){e=e??{};let t=e.onEnd,n=new An,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new An,s!=null?s({error:y}):(n.push({error:y}),o)),l=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},p=y=>i?o:(i=!0,y!=null?f(y):u({done:!0})),h=()=>(n=new An,p(),{done:!0}),d=y=>(p(y),{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 y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let w,b;g!=null&&(w=new Promise((x,v)=>{b=()=>{v(new El)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}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(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(y){return m.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}var xl=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 Sn(r,e,t,n){let o=new xl(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 Ei=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 hr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Ei(t?.errorMessage,t?.errorCode));let n,o=new Ei(t?.errorMessage,t?.errorCode);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 xi=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 zt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function mw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var vi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=mw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,fe(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 zt),this.cleanup())}async join(e={}){let t=new xi(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 hr(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 Rn=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 vi(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 zt)}),this.clear()}async onEmpty(e){this.size!==0&&await Sn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Sn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Sn(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=bi({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 _i=class extends Rn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ai="last-dial-failure";var Si=5,Ri=100,Ii=50,Bi=1e3*60*7;var Or={minConnections:Si,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Bi,autoDialDiscoveredPeersDebounce:10},Ti=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??Or.minConnections,this.autoDialPriority=t.autoDialPriority??Or.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Or.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Or.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Or.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Or.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new _i({concurrency:t.autoDialConcurrency??Or.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 Ft(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(Ai);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 yw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Dd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??yw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Pd={maxConnections:Ri,allow:[]},Ci=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Pd.maxConnections,this.allow=t.allow??Pd.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 Dd(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 ki=class extends Rn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function yo(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 Od(r,e){let t=!1;for(let o of gn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var wo={addressSorter:xn,maxParallelDials:Ii,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Pr}},Ni=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??wo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??wo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??wo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??wo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,fe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))gn.set(n,o);this.queue=new ki({concurrency:t.maxParallelDials??wo.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,fe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=yi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new de("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new 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 de("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new de("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new de("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let 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",C.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:{[Ai]: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,Io);l.push(h)}}throw l.length===1?l[0]:new Ro(l,"All multiaddr dials failed",C.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Tl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=yo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return fe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:se(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new E("Tried to dial self",C.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",C.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!==C.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!==C.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 Od(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",C.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",C.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=>!go.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Tl=50,Ht={minConnections:Si,maxConnections:Ri,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Bi,autoDialDiscoveredPeersDebounce:10},Li=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Ht.maxConnections;let n=t.minConnections??Ht.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",C.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=>se(o)),this.deny=(t.deny??[]).map(o=>se(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Ht.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new gi({points:t.inboundConnectionThreshold??Ht.inboundConnectionThreshold,duration:1}),this.autoDial=new Ti({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Ht.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Ht.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Ht.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Ht.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Ht.autoDialMaxQueueLength}),this.connectionPruner=new Ci({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ni(e,{addressSorter:t.addressSorter??xn,maxParallelDials:t.maxParallelDials??Ii,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Pr},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(Zl)]});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",C.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=yi(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 de("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Tl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>se(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};function Ew(r){return r[Symbol.asyncIterator]!=null}function xw(...r){let e=[];for(let t of r)Ew(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=bi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var bo=xw;var Di=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",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Ft;for await(let s of bo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",C.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(Kt.NOT_STARTED_YET,C.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(Kt.NOT_STARTED_YET,C.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Pi=globalThis.CustomEvent??Event;async function*Cl(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(y=>{m.done=!0,m.ok=!0,m.value=y,o.dispatchEvent(new Pi("task-complete"))},y=>{m.done=!0,m.err=y,o.dispatchEvent(new Pi("task-complete"))})}c=!0,o.dispatchEvent(new Pi("task-complete"))}catch(d){u=d,o.dispatchEvent(new Pi("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 Oi=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",C.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",C.ERR_FIND_SELF);let n=this,o=bo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Kt.NOT_FOUND,C.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",C.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Rc(1024);for await(let s of Cl(async function*(){let i=bo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var Ui=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,fe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,fe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=yo([this.shutdownController.signal,e?.signal]);fe(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Sn(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,fe(1/0,this.walkController.signal);let e=yo([this.walkController.signal,this.shutdownController.signal]);fe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=yt(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 hr(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 kl=32,Nl=64,Mi=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}`,C.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}`,C.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=mi.bind({ignoreUndefined:!0})({maxInboundStreams:kl,maxOutboundStreams:Nl},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",C.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!==C.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 Ll=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 Ud(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ll({name:e,metrics:t}):n=new Map,n}var Fi=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=Ud({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??qt.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",C.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,C.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)}`,C.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new de("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=C.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",C.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!==qt.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,C.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===qt.FATAL_ALL)throw new E(n,C.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var ke="/multistream/1.0.0";var Dl=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 hr(this.readNext.promise,t?.signal,t)}};function Md(){return new Dl}var Vi=class extends Error{code;constructor(e,t){super(e),this.code=t}},Pl=class extends Vi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Fd(r,e){let t=Md();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 Ee;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new Pl("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 Ee: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","ERR_UNEXPECTED_EOF");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 Ki=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Eo(r,e={}){let t=Fd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??at,o=e?.lengthEncoder??Pe;return{read:async i=>{let a=-1,c=new Ee;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ki("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ki("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new Ee(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Ee(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var vw=L(`
|
|
8
|
-
`);async function
|
|
6
|
+
`)}`:`${t} :`}};wf=er;C.Constructed=wf;er.NAME="CONSTRUCTED";var os=class extends Pe{fromBER(e,t,n){return t}toBER(e){return ft}};os.override="EndOfContentValueBlock";var bf,ss=class extends Ie{constructor(e={}){super(e,os),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};bf=ss;C.EndOfContent=bf;ss.NAME=$n;var Ef,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}`}};Ef=tr;C.Null=Ef;tr.NAME="NULL";var is=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,dc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};is.NAME="BooleanValueBlock";var xf,as=class extends Ie{constructor(e={}){super(e,is),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}`}};xf=as;C.Boolean=xf;as.NAME="BOOLEAN";var cs=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===$n){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==pf)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}}};cs.NAME="OctetStringValueBlock";var vf,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},cs),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=Os(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)}};vf=Dt;C.OctetString=vf;Dt.NAME=pf;var ls=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===$n){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==mf)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=Os(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 ft;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}}};ls.NAME="BitStringValueBlock";var _f,on=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},ls),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)}`}}};_f=on;C.BitString=_f;on.NAME=mf;var Af;function n0(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=Zo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Zo(t,s)),s}function df(r){if(r>=Kn.length)for(let e=Kn.length;e<=r;e++){let t=new Uint8Array([0]),n=Kn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=Zo(t,n)),Kn.push(n)}return Kn[r]}function o0(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 qn=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=dc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(uf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=o0(df(n),t),i="-";break;default:t=n0(t,df(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=hf.charAt(t[c]));return a===!1&&(i+=hf.charAt(0)),i}};Af=qn;qn.NAME="IntegerValueBlock";Object.defineProperty(Af.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Sf,pe=class r extends Ie{constructor(e={}){super(e,qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Qo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Qo();let t=BigInt(e),n=new Hn,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()}`}};Sf=pe;C.Integer=Sf;pe.NAME="INTEGER";var Rf,us=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Rf=us;C.Enumerated=Rf;us.NAME="ENUMERATED";var zn=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){Qo();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",ft;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}}};zn.NAME="sidBlock";var fs=class extends Pe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new zn;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,ft;t.push(o)}return pc(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 zn;if(o>Number.MAX_SAFE_INTEGER){Qo();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}};fs.NAME="ObjectIdentifierValueBlock";var If,ut=class extends Ie{constructor(e={}){super(e,fs),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()}}};If=ut;C.ObjectIdentifier=If;ut.NAME="OBJECT IDENTIFIER";var Gn=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",ft;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}}};Gn.NAME="relativeSidBlock";var hs=class extends Pe{constructor({value:e=sn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Gn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.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,ft;n.push(s)}return pc(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 Gn;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}};hs.NAME="RelativeObjectIdentifierValueBlock";var Bf,ds=class extends Ie{constructor(e={}){super(e,hs),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()}}};Bf=ds;C.RelativeObjectIdentifier=Bf;ds.NAME="RelativeObjectIdentifier";var Tf,_e=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Tf=_e;C.Sequence=Tf;_e.NAME="SEQUENCE";var Cf,ps=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Cf=ps;C.Set=Cf;ps.NAME="SET";var ms=class extends Ut(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=sn}toJSON(){return{...super.toJSON(),value:this.value}}};ms.NAME="StringValueBlock";var gs=class extends ms{};gs.NAME="SimpleStringValueBlock";var Ke=class extends ts{constructor({...e}={}){super(e,gs)}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 ys=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}};ys.NAME="Utf8StringValueBlock";var kf,Pt=class extends ys{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};kf=Pt;C.Utf8String=kf;Pt.NAME="UTF8String";var ws=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))}};ws.NAME="BmpStringValueBlock";var Nf,bs=class extends ws{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Nf=bs;C.BmpString=Nf;bs.NAME="BMPString";var Es=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}};Es.NAME="UniversalStringValueBlock";var Lf,xs=class extends Es{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Lf=xs;C.UniversalString=Lf;xs.NAME="UniversalString";var Df,vs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Df=vs;C.NumericString=Df;vs.NAME="NumericString";var Pf,_s=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Pf=_s;C.PrintableString=Pf;_s.NAME="PrintableString";var Of,As=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Of=As;C.TeletexString=Of;As.NAME="TeletexString";var Uf,Ss=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Uf=Ss;C.VideotexString=Uf;Ss.NAME="VideotexString";var Mf,Rs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Mf=Rs;C.IA5String=Mf;Rs.NAME="IA5String";var Ff,Is=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ff=Is;C.GraphicString=Ff;Is.NAME="GraphicString";var Vf,Yn=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Vf=Yn;C.VisibleString=Vf;Yn.NAME="VisibleString";var Kf,Bs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Kf=Bs;C.GeneralString=Kf;Bs.NAME="GeneralString";var Hf,Ts=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Hf=Ts;C.CharacterString=Hf;Ts.NAME="CharacterString";var $f,Wn=class extends Yn{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}}};$f=Wn;C.UTCTime=$f;Wn.NAME="UTCTime";var qf,Cs=class extends Wn{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}}};qf=Cs;C.GeneralizedTime=qf;Cs.NAME="GeneralizedTime";var zf,ks=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};zf=ks;C.DATE=zf;ks.NAME="DATE";var Gf,Ns=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Gf=Ns;C.TimeOfDay=Gf;Ns.NAME="TimeOfDay";var Yf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Yf=Ls;C.DateTime=Yf;Ls.NAME="DateTime";var Wf,Ds=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Wf=Ds;C.Duration=Wf;Ds.NAME="Duration";var jf,Ps=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};jf=Ps;C.TIME=jf;Ps.NAME="TIME";function i0(r){let{result:e}=an(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 a0(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 c0(r){let{result:e}=an(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 l0(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 ut({value:"1.2.840.113549.1.1.1"}),new tr]}),new on({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 u0=16,gc=32,yc=1e4;async function f0(r,e){let t=Ue.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ut({value:"1.2.840.113549.1.1.1"}),new tr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=wt(u0),a=await fc(Ln,e,i,{c:yc,dkLen:gc}),c=wt(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:yc}),new pe({value:gc}),new _e({value:[new ut({value:"1.2.840.113549.2.11"}),new tr]})]}),p=new _e({value:[new ut({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new ut({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new ut({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 h0(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}=an(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=d0(s),l=await fc(Ln,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=jn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=an(h);n=Xf(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}=an(o);n=Xf(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return wc(n)}function d0(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=jn(s.valueBlock.value[0].getValue()),a=yc,c=gc;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=jn(u.valueBlock.value[1].getValue());return{cipherText:jn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Xf(r){return jn(r.valueBlock.value[2].getValue())}function jn(r){return new Uint8Array(r,0,r.byteLength)}async function Zf(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 eh(e);return{privateKey:t[0],publicKey:t[1]}}async function bc(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await p0(r)],n=await eh({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Qf(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 Jf(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 eh(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 p0(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 Us(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 Zn=8192,Xn=class{_key;constructor(e){this._key=e}verify(e,t){return Jf(this._key,t,e)}marshal(){return rr.jwkToPkix(this._key)}get bytes(){return gt.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}},cn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return wt(16)}sign(e){return Qf(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Xn(this._publicKey)}marshal(){return rr.jwkToPkcs1(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}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 en(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function wc(r){let e=rr.pkcs1ToJwk(r);if(Us(e)>Zn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await bc(e);return new cn(t.privateKey,t.publicKey)}function g0(r){let e=rr.pkixToJwk(r);if(Us(e)>Zn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Xn(e)}async function y0(r){if(Us(r)>Zn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await bc(r);return new cn(e.privateKey,e.publicKey)}async function w0(r){if(r>Zn)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Zf(r);return new cn(e.privateKey,e.publicKey)}var Sc={};ve(Sc,{Secp256k1PrivateKey:()=>Jn,Secp256k1PublicKey:()=>Qn,generateKeyPair:()=>k0,unmarshalSecp256k1PrivateKey:()=>T0,unmarshalSecp256k1PublicKey:()=>C0});var b0=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),xc=class extends Xr{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=st(p,7)^st(p,18)^p>>>3,m=st(h,17)^st(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=st(a,6)^st(a,11)^st(a,25),h=f+p+Nu(a,c,u)+b0[l]+or[l]|0,m=(st(n,2)^st(n,13)^st(n,22))+Lu(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 th=Po(()=>new xc);function rh(r){r.lowS!==void 0&&it("lowS",r.lowS),r.prehash!==void 0&&it("prehash",r.prehash)}function E0(r){let e=On(r);mt(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:x0,hexToBytes:v0}=Mo,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:x0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?v0(r):r;Zr(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),M1=BigInt(2),nh=BigInt(3),F1=BigInt(4);function _0(r){let e=E0(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 Dn(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=Bt(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:Tt(ce("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(ce("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,nh),{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,nh),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 it("isCompressed",m),this.assertValidity(),n(l,this,m)}toHex(m=!0){return it("isCompressed",m),Bt(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=Ko(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function A0(r){let e=On(r);return mt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function oh(r){let e=A0(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 Fo(N,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=_0({...e,toBytes(N,S,v){let B=S.toAffine(),T=t.toBytes(B.x),P=Ct;return it("isCompressed",v),v?P(Uint8Array.from([S.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,t.toBytes(B.y))},fromBytes(N){let S=N.length,v=N[0],B=N.subarray(1);if(S===o&&(v===2||v===3)){let T=Tt(B);if(!Dn(T,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(T),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:T,y:O}}else if(S===s&&v===4){let T=t.fromBytes(B.subarray(0,t.BYTES)),P=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:T,y:P}}else throw new Error(`Point of length ${S} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=N=>Bt(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)=>Tt(N.slice(S,v));class w{constructor(S,v,B){this.r=S,this.s=v,this.recovery=B,this.assertValidity()}static fromCompact(S){let v=e.nByteLength;return S=ce("compactSignature",S,v*2),new w(m(S,0,v),m(S,v,2*v))}static fromDER(S){let{r:v,s:B}=Rr.toSig(ce("DER",S));return new w(v,B)}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:B,recovery:T}=this,P=R(ce("msgHash",S));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");let O=T===2||T===3?v+e.n:v;if(O>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=T&1?"03":"02",z=c.fromHex(U+p(O)),H=a(O),G=i(-P*H),oe=i(B*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=Va(e.n);return Hu(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",B=(S||v)&&N.length;return S?B===o||B===s:v?B===2*o||B===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=Tt(N),v=N.length*8-e.nBitLength;return v>0?S>>BigInt(v):S},R=e.bits2int_modN||function(N){return i(A(N))},_=Pn(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:B,randomBytes:T}=e,{lowS:P,prehash:O,extraEntropy:U}=v;P==null&&(P=!0),N=ce("msgHash",N),rh(v),O&&(N=ce("prehashed msgHash",B(N)));let z=R(N),H=u(S),G=[I(H),I(z)];if(U!=null&&U!==!1){let Ee=U===!0?T(t.BYTES):U;G.push(ce("extraEntropy",Ee))}let oe=Ct(...G),se=z;function $e(Ee){let me=A(Ee);if(!l(me))return;let rt=a(me),xe=c.BASE.multiply(me).toAffine(),nt=i(xe.x);if(nt===sr)return;let dr=i(rt*i(se+nt*H));if(dr===sr)return;let Bn=(xe.x===nt?0:2)|Number(xe.y&Ae),So=dr;return P&&h(dr)&&(So=d(dr),Bn^=1),new w(nt,So,Bn)}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:B,k2sig:T}=$(N,S,v),P=e;return Oa(P.hash.outputLen,P.nByteLength,P.hmac)(B,T)}c.BASE._setWindowSize(8);function D(N,S,v,B=K){let T=N;if(S=ce("msgHash",S),v=ce("publicKey",v),"strict"in B)throw new Error("options.strict was renamed to lowS");rh(B);let{lowS:P,prehash:O}=B,U,z;try{if(typeof T=="string"||jt(T))try{U=w.fromDER(T)}catch(xe){if(!(xe instanceof Rr.Err))throw xe;U=w.fromCompact(T)}else if(typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint"){let{r:xe,s:nt}=T;U=new w(xe,nt)}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 S0(r){return{hash:r,hmac:(e,...t)=>Vn(r,e,Ta(...t)),randomBytes:jr}}function sh(r,e){let t=n=>oh({...r,...S0(n)});return Object.freeze({...t(e),create:t})}var ch=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ih=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),R0=BigInt(1),vc=BigInt(2),ah=(r,e)=>(r+e/vc)/e;function I0(r){let e=ch,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,vc,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,vc,e);if(!_c.eql(_c.sqr(R),r))throw new Error("Cannot find square root");return R}var _c=Vo(ch,void 0,void 0,{sqrt:I0}),ht=sh({a:BigInt(0),b:BigInt(7),Fp:_c,n:ih,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=ih,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-R0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=ah(s*r,e),c=ah(-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}}}},th),W1=BigInt(0);var j1=ht.ProjectivePoint;function lh(){return ht.utils.randomPrivateKey()}function uh(r,e){let t=Se.digest(e instanceof Uint8Array?e:e.subarray());if(Je(t))return t.then(({digest:n})=>ht.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return ht.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function fh(r,e,t){let n=Se.digest(t instanceof Uint8Array?t:t.subarray());if(Je(n))return n.then(({digest:o})=>ht.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return ht.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function hh(r){return ht.ProjectivePoint.fromHex(r).toRawBytes(!0)}function dh(r){try{ht.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Ac(r){try{ht.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function ph(r){try{return ht.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Qn=class{_key;constructor(e){Ac(e),this._key=e}verify(e,t){return fh(this._key,t,e)}marshal(){return hh(this._key)}get bytes(){return gt.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}},Jn=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??ph(e),dh(this._key),Ac(this._publicKey)}sign(e){return uh(this._key,e)}get public(){return new Qn(this._publicKey)}marshal(){return this._key}get bytes(){return yt.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 en(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function T0(r){return new Jn(r)}function C0(r){return new Qn(r)}async function k0(){let r=lh();return new Jn(r)}var ir={rsa:Ec,ed25519:uc,secp256k1:Sc};function Rc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Ic(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw Rc(r)}async function mh(r,e){return Ic(r).generateKeyPair(e??2048)}function eo(r){let e=gt.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 Rc(e.Type??"unknown")}}function gh(r,e){return e=(e??"rsa").toLowerCase(),Ic(e),r.bytes}async function to(r){let e=yt.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 Rc(e.Type??"RSA")}}function yh(r,e){return e=(e??"rsa").toLowerCase(),Ic(e),r.bytes}function N0(r,e){try{if(typeof r=="string"&&r.length>0)return L0(r);if(typeof r=="number"&&isFinite(r))return e?.long?P0(r):D0(r);throw new Error("Value is not a string or number.")}catch(t){let n=O0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function L0(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 Fs=N0;function D0(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 P0(r){let e=Math.abs(r);return e>=864e5?Ms(r,e,864e5,"day"):e>=36e5?Ms(r,e,36e5,"hour"):e>=6e4?Ms(r,e,6e4,"minute"):e>=1e3?Ms(r,e,1e3,"second"):`${r} ms`}function Ms(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function O0(r){return typeof r=="object"&&r!==null&&"message"in r}function Bc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Fs,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 Vs=$0(),U0=["#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 M0(){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 F0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Fs(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 V0=console.debug??console.log??(()=>{});function K0(r){try{r?Vs?.setItem("debug",r):Vs?.removeItem("debug")}catch{}}function H0(){let r;try{r=Vs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function $0(){try{return localStorage}catch{}}function q0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var wh=Bc({formatArgs:F0,save:K0,load:H0,useColors:M0,setupFormatters:q0,colors:U0,storage:Vs,log:V0});var je=wh;je.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);je.formatters.t=r=>r==null?"undefined":Ye.baseEncode(r);je.formatters.m=r=>r==null?"undefined":kn.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 z0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ks(){return{forComponent(r){return G0(r)}}}function G0(r){let e=z0(`${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 Eh=Symbol.for("nodejs.util.inspect.custom"),bh=Object.values(zt).map(r=>r.decoder).reduce((r,e)=>r.or(e),zt.identity.decoder),xh=114,kc=36,Nc=37,ro=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()})`}[Io]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Qe.createV1(xh,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")}[Eh](){return`PeerId(${this.toString()})`}},Ir=class extends ro{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Br=class extends ro{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Tr=class extends ro{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Tc=2336,Cc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Rt.digest(L(this.url))}[Eh](){return`PeerId(${this.url})`}[Io]=!0;toString(){return this.toCID().toString()}toCID(){return Qe.createV1(Tc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function vh(r){if(r.type==="RSA")return new Ir(r);if(r.type==="Ed25519")return new Br(r);if(r.type==="secp256k1")return new Tr(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??bh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ie.decode(`z${r}`));return r.startsWith("12D")?new Br({multihash:t}):r.startsWith("16U")?new Tr({multihash:t}):new Ir({multihash:t})}return ln(bh.decode(r))}function ln(r){try{let e=mr(r);if(e.code===Rt.code){if(e.digest.length===kc)return new Br({multihash:e});if(e.digest.length===Nc)return new Tr({multihash:e})}if(e.code===Se.code)return new Ir({multihash:e})}catch{return Y0(Qe.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Y0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==xh&&r.code!==Tc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Tc){let t=F(r.multihash.digest);return new Cc(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===kc)return new Br({multihash:r.multihash});if(e.digest.length===Nc)return new Tr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function un(r,e){return r.length===kc?new Br({multihash:pt(Rt.code,r),privateKey:e}):r.length===Nc?new Tr({multihash:pt(Rt.code,r),privateKey:e}):new Ir({multihash:await Se.digest(r),publicKey:r,privateKey:e})}function fn(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 fn(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 fn(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 fn(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 fn(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 Ih=Symbol.for("@achingbrain/uint8arraylist");function Rh(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 $s(r){return!!r?.[Ih]}var we=class r{bufs;length;[Ih]=!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($s(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($s(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=Rh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Rh(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($s(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(!$s(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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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=ot(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 Lc=64,dt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Lc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ot(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 dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dt))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 dt))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 dt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Bh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Th=new globalThis.TextEncoder;function W0(r,e){let t=Dc[e],n=Bh[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=Dc[e],o=Bh[e],s=r;for(;s.length>0;){let i=Th.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 Pc(r,{size:e=32,utf8Buffer:t}={}){if(!Dc[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=Th.encode(r)}return W0(r,e)}var X0=pr(Sh(),1);var oo={hash:r=>Number(Pc(r,{size:32})),hashV:(r,e)=>Z0(oo.hash(r,e))};function Z0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var Q0=500,so=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??oo,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new dt(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<Q0;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 dt(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 dt(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}},J0={1:.5,2:.84,4:.95,8:.98};function ey(r=.001){return r>.002?2:r>1e-5?4:8}function Ch(r,e=.001){let t=ey(e),n=J0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Lc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var qs=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??oo,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new so({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 so({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 Oc(r,e=.001,t){return new qs({...Ch(r,e),...t??{}})}var kh=async()=>{let r=await mh("Ed25519"),e=await ty(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function ty(r){return un(gh(r.public),yh(r))}var Nh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var io;(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())})(io||(io={}));var hn=class r{static createFromProtobuf=async e=>{let t=io.decode(e),n=await un(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=Lh(n,o,s),c=await(await to(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",Nh.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=io.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=Lh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return eo(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Lh=(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 Dh(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 zs=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 Ph=45,ry=15,dn=new zs;function Uc(r){if(!(r.length>ry))return dn.new(r).parseWith(()=>dn.readIPv4Addr())}function Mc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ph))return dn.new(r).parseWith(()=>dn.readIPv6Addr())}function Gs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ph))return dn.new(r).parseWith(()=>dn.readIPAddr())}var W_=parseInt("0xFFFF",16),j_=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function pn(r){return!!Uc(r)}function mn(r){return!!Mc(r)}function Ys(r){return!!Gs(r)}var Mh=pn,ay=mn,Fc=function(r){let e=0;if(r=r.toString().trim(),Mh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(ay(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Mh(t[n]),i;s&&(i=Fc(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")},Fh=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 gn={},Vc={},ly=[[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"]];ly.forEach(r=>{let e=uy(...r);Vc[e.code]=e,gn[e.name]=e});function uy(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function j(r){if(typeof r=="number"){if(Vc[r]!=null)return Vc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(gn[r]!=null)return gn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var NA=j("ip4"),LA=j("ip6"),DA=j("ipcidr");function qc(r,e){switch(j(r).code){case 4:case 41:return hy(e);case 42:return $c(e);case 6:case 273:case 33:case 132:return Hh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $c(e);case 421:return gy(e);case 444:return Kh(e);case 445:return Kh(e);case 466:return my(e);case 481:return globalThis.encodeURIComponent($c(e));default:return F(e,"base16")}}function zc(r,e){switch(j(r).code){case 4:return Vh(e);case 41:return Vh(e);case 42:return Hc(e);case 6:case 273:case 33:case 132:return Gc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Hc(e);case 421:return dy(e);case 444:return yy(e);case 445:return wy(e);case 466:return py(e);case 481:return Hc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var Kc=Object.values(zt).map(r=>r.decoder),fy=function(){let r=Kc[0].or(Kc[1]);return Kc.slice(2).forEach(e=>r=r.or(e)),r}();function Vh(r){if(!Ys(r))throw new Error("invalid ip address");return Fc(r)}function hy(r){let e=Fh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ys(e))throw new Error("invalid ip address");return e}function Gc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Hh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Hc(r){let e=L(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function $c(r){let e=ct(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function dy(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ie.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 py(r){let e=fy.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function my(r){let e=ct(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function gy(r){let e=ct(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function yy(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=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=Gc(n);return Re([t,o],t.length+o.length)}function wy(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=Gc(n);return Re([t,o],t.length+o.length)}function Kh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Hh(t);return`${n}:${o}`}function $h(r){r=Yc(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 zh("invalid address: "+r);if(a.path===!0){n=Yc(o.slice(s).join("/")),e.push([a.code,zc(a.code,n)]),t.push([a.code,n]);break}let c=zc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,qc(a.code,c)])}return{string:qh(t),bytes:jc(e),tuples:e,stringTuples:t,path:n}}function Wc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=ct(r,o),i=de(s),a=j(s),c=by(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw zh("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=qc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:qh(t),tuples:e,stringTuples:t,path:n}}function qh(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}),Yc(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 by(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=ct(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function Yc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function zh(r){return new Error("Error parsing address: "+r)}var Ey=Symbol.for("nodejs.util.inspect.custom"),Xc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),xy=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Ws=class r{bytes;#e;#t;#s;#a;[Xc]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Wc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=$h(e)}else if(ar(e))t=Wc(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??""}`),xy.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===gn.p2p.code&&e.push([n,o]),n===gn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?F(ie.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=yn.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)}[Ey](){return`Multiaddr(${this.#e})`}};var yn=new Map;function ar(r){return!!r?.[Xc]}function ne(r){return new Ws(r)}var Gh="libp2p-peer-record",Yh=Uint8Array.from([3,1]);var ao;(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())})(ao||(ao={}));var Nr=class r{static createFromProtobuf=e=>{let t=ao.decode(e),n=ln(t.peerId),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Gh;static CODEC=Yh;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=ao.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||!Dh(this.multiaddrs,e.multiaddrs))}};function vy(r){return r[Symbol.asyncIterator]!=null}function _y(r){if(vy(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 co=_y;var Qc=pr(jh(),1);var uo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Jc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Xh=r=>globalThis.DOMException===void 0?new Jc(r):new DOMException(r),Zh=r=>{let e=r.reason===void 0?Xh("This operation was aborted."):r.reason;return e instanceof Error?e:Xh(e)};function fo(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(Zh(p)),p.addEventListener("abort",()=>{f(Zh(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new uo;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 el(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 ho=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=el(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 Qc.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:ho,...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=fo(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 uo&&!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={},wn=r=>{r.addEventListener("message",e=>{wn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{wn.dispatchEvent("message",r,e)})};wn.addEventListener=(r,e)=>{lr[r]==null&&(lr[r]=[]),lr[r].push(e)};wn.removeEventListener=(r,e)=>{lr[r]!=null&&(lr[r]=lr[r].filter(t=>t===e))};wn.dispatchEvent=function(r,e,t){lr[r]!=null&&lr[r].forEach(n=>n(e,t))};var tl=wn;var rl="lock:worker:request-read",nl="lock:worker:release-read",ol="lock:master:grant-read",sl="lock:worker:request-write",il="lock:worker:release-write",al="lock:master:grant-write";var Qh=(r=21)=>Math.random().toString().substring(2);var Jh=(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)})}}}))},ed=(r,e,t,n)=>async()=>{let o=Qh();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)})},Ry={singleProcess:!1},td=r=>{if(r=Object.assign({},Ry,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return tl.addEventListener("message",Jh(t,"requestReadLock",rl,nl,ol)),tl.addEventListener("message",Jh(t,"requestWriteLock",sl,il,al)),t}return{isWorker:!0,readLock:t=>ed(t,rl,ol,nl),writeLock:t=>ed(t,sl,al,il)}};var Lr={},ur;async function cl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>fo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Iy=(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 cl(n,e);n=new cr({concurrency:e.concurrency,autoStart:!1});let o=n,s=cl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,cl(t,e)}}},By={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ll(r){let e=Object.assign({},By,r);return ur==null&&(ur=td(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]=Iy(e.name,e)),Lr[e.name]}var Be={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var bn;(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),Zs.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=Zs.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),Xs.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(Xs.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())})(bn||(bn={}));var Xs;(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())})(Xs||(Xs={}));var Zs;(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())})(Zs||(Zs={}));function En(r,e){let t=bn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=vh({...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="/",rd=new TextEncoder().encode(Ft),Qs=rd[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]!==Qs)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=rd),this._buf[0]!==Qs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Qs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Qs;)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 Ty(this.baseNamespace())}name(){return Cy(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(),...ky(e.map(t=>t.namespaces()))])}};function Ty(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Cy(r){let e=r.split(":");return e[e.length-1]}function ky(r){return[].concat(...r)}var ul="/peers/";function xn(r){if(!Bo(r)||r.type==null)throw new E("Invalid PeerId",Be.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${ul}${e}`)}async function nd(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",Be.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function ei(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Be.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",Be.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",Be.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Js(l,{validate:od})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Js(l,{validate:sd,map:id})}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=Js([...a.entries()],{validate:od})}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=Js([...p.entries()],{validate:sd,map:id})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await nd(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 Js(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 od(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Be.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Be.ERR_INVALID_PARAMETERS)}function sd(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Be.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Be.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Be.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Be.ERR_INVALID_PARAMETERS)}}function id(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 ti(r,e,t){let n=r.toString().split("/")[2],o=Ye.decode(n),s=ln(o),i=t.get(s);if(i!=null)return i;let a=En(s,e);return t.set(s,a),a}function Ny(r,e){return r==null?{}:{prefix:ul,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ti(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ti(n.key,n.value,e),ti(o.key,o.value,e)))}}var ri=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=ll({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(xn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Be.ERR_INVALID_PARAMETERS);await this.datastore.delete(xn(e))}async load(e){let t=await this.datastore.get(xn(e));return En(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ei(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 ei(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 ei(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(Ny(e??{},t))){let s=ti(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(xn(e)),n=En(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=bn.encode(t);return n!=null&&J(s,n)?{peer:En(e,s),previous:o,updated:!1}:(await this.datastore.put(xn(e),s),{peer:En(e,s),previous:o,updated:!0})}};var ni=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 ri(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 co(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 hn.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 hn.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 Ly(r){return r[Symbol.asyncIterator]!=null}function Dy(r){if(Ly(r))return(async()=>{for await(let e of r);})();for(let e of r);}var fl=Dy;function Py(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 ad=Py;function Oy(r){return r[Symbol.asyncIterator]!=null}function Uy(r,e){let t=0;if(Oy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ad(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=Uy;function My(r){return r[Symbol.asyncIterator]!=null}function Fy(r,e){return My(r)?async function*(){yield*(await co(r)).sort(e)}():function*(){yield*co(r).sort(e)}()}var hl=Fy;function Vy(r){return r[Symbol.asyncIterator]!=null}function Ky(r,e){return Vy(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 dl=Ky;var oi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await fl(this.putMany(e,n)),e=[],await fl(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)=>hl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=dl(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)=>hl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=dl(n,e.limit)),n}};var fd=pr(ud(),1);function hd(r){return r=r??new Error("Not Found"),(0,fd.default)(r,"ERR_NOT_FOUND")}var si=class extends oi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw hd();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 dd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var qy=r=>r;function pl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var ii=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??qy,this._updatePeerStoreAddresses=dd(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=pl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=pl(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=pl(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 ml=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=Ks())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>au(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},zy=["metrics","connectionProtector","dns"],Gy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function pd(r={}){let e=new ml(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Gy.includes(o)){let i=e.components[o];if(i==null&&!zy.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 md(r){let e={};for(let t of Object.values(r.components))for(let n of Yy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Wy(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 Yy(r){return Array.isArray(r?.[sa])?r[sa]:[]}function Wy(r){return Array.isArray(r?.[ia])?r[ia]:[]}function jy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var yd=pr(gd(),1),Xy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Zy=Xy.map(r=>new yd.Netmask(r));function gl(r){for(let e of Zy)if(e.contains(r))return!0;return!1}function Qy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Jy(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 gl(o)}function ew(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function tw(r){let e=r.split(":"),t=e[e.length-1];return gl(t)}function rw(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 ai(r){return pn(r)?gl(r):Qy(r)?Jy(r):ew(r)?tw(r):mn(r)?rw(r):void 0}function wd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ai(`${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 nw=r=>r.toString().split("/").slice(1),mo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>mo(t=>t===r).match(e),pattern:r}),ui=()=>({match:r=>mo(e=>typeof e=="string").match(r),pattern:"{string}"}),fi=()=>({match:r=>mo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Te=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ie.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ci=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{_a.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})`}),tt=(...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=nw(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 wl=Z(Y("dns4"),ui()),bl=Z(Y("dns6"),ui()),El=Z(Y("dnsaddr"),ui()),bd=Z(Y("dns"),ui()),sR=fe(wl),iR=fe(bl),aR=fe(El),cR=fe(tt(bd,El,wl,bl)),Ed=Z(Y("ip4"),mo(pn)),xd=Z(Y("ip6"),mo(mn)),vd=tt(Ed,xd),vt=tt(vd,bd,wl,bl,El),lR=fe(vt),uR=fe(Ed),fR=fe(xd),hR=fe(vd),xl=Z(vt,Y("tcp"),fi()),go=Z(vt,Y("udp"),fi()),dR=fe(xl),pR=fe(go),vl=Z(go,Y("quic")),hi=Z(go,Y("quic-v1")),ow=tt(vl,hi),mR=fe(vl),gR=fe(hi),yl=tt(vt,xl,go,vl,hi),_d=tt(Z(yl,Y("ws"),be(Te()))),yR=fe(_d),Ad=tt(Z(yl,Y("wss"),be(Te())),Z(yl,Y("tls"),Y("ws"),be(Te()))),wR=fe(Ad),Sd=Z(go,Y("webrtc-direct"),be(ci()),be(ci()),be(Te())),bR=fe(Sd),Rd=Z(hi,Y("webtransport"),be(ci()),be(ci()),be(Te())),ER=fe(Rd),li=tt(_d,Ad,Z(xl,be(Te())),Z(ow,be(Te())),Z(vt,be(Te())),Sd,Rd,Te()),xR=fe(li),sw=Z(li,Y("p2p-circuit"),Te()),yo=fe(sw),iw=tt(Z(li,Y("p2p-circuit"),Y("webrtc"),be(Te())),Z(li,Y("webrtc"),be(Te())),Y("webrtc")),vR=fe(iw),aw=tt(Z(vt,Y("tcp"),fi(),Y("http"),be(Te())),Z(vt,Y("http"),be(Te()))),_R=fe(aw),cw=tt(Z(vt,Y("tcp"),tt(Z(Y("443"),Y("http")),Z(fi(),Y("https"))),be(Te())),Z(vt,Y("tls"),Y("http"),be(Te())),Z(vt,Y("https"),be(Te()))),AR=fe(cw);function _l(r){try{let{address:e}=r.nodeAddress();return!!ai(e)}catch{return!0}}function lw(r,e){let t=_l(r.multiaddr),n=_l(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function uw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function fw(r,e){let t=yo.exactMatch(r.multiaddr),n=yo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vn(r,e){let t=lw(r,e);if(t!==0)return t;let n=fw(r,e);return n!==0?n:uw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function di(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Al=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(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??Al,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var hw=4;function Sl(r,e={}){let t=new cr({concurrency:e.queryConcurrency??hw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),di(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=pi(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 Id(){return[Sl("https://cloudflare-dns.com/dns-query"),Sl("https://dns.google/resolve")]}var Cd=pr(Td(),1);var Rl=class{lru;constructor(e){this.lru=(0,Cd.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 pi({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??Al)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function kd(r){return new Rl(r)}var dw=1e3,mi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=kd(e.cacheSize??dw),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["."]=Id())}async query(e,t={}){let n=di(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 Nd(r={}){return new mi(r)}var pw=32,{code:mw}=j("dnsaddr"),Or=async function(e,t={}){let n=t.maxRecursiveDepth??pw;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===mw)??[],i=await(t?.dns??Nd()).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 Kd=pr(Vd(),1),wi=Kd.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 xw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Or},addressSorter:vn},transportManager:{faultTolerance:Ht.FATAL_ALL}};async function Hd(r){let e=wi(xw,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 un(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 $d=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},vw=new WeakMap;function _w({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject($d());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a($d())},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}),vw.set(l,()=>{c(s),s=null,i()}),l}}var Aw=_w(),qd=Aw;var bi=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 Bl}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 qd(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)}},Bl=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 Ei(r){if(Bo(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 le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var xi=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}},Sn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new xi(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 xi(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 Tl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function vi(r={}){return Sw(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 Sw(r,e){e=e??{};let t=e.onEnd,n=new Sn,o,s,i,a=le(),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=le()})}},u=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new Sn,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 Sn,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 Tl)},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 Cl=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 Rn(r,e,t,n){let o=new Cl(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 _i=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 _i(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new _i(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 Ai=class{deferred;signal;constructor(e){this.signal=e,this.deferred=le(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Rw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Si=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Rw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ue(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 Ai(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 In=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 Si(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 Rn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Rn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Rn(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=vi({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 Ri=class extends In{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ii="last-dial-failure";var Bi=5,Ti=100,Ci=50,ki=1e3*60*7;var Ur={minConnections:Bi,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:ki,autoDialDiscoveredPeersDebounce:10},Ni=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 Ri({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(Ii);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 Bw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function zd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Bw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Gd={maxConnections:Ti,allow:[]},Li=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Gd.maxConnections,this.allow=t.allow??Gd.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 zd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Di=class extends In{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function wo(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 Yd(r,e){let t=!1;for(let o of yn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var bo={addressSorter:vn,maxParallelDials:Ci,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Or}},Pi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??bo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??bo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??bo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??bo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))yn.set(n,o);this.queue=new Di({concurrency:t.maxParallelDials??bo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ue(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Ei(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:{[Ii]: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,Co);l.push(h)}}throw l.length===1?l[0]:new To(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Ml,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=wo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ue(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 Yd(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=>!yo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Ml=50,Kt={minConnections:Bi,maxConnections:Ti,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:ki,autoDialDiscoveredPeersDebounce:10},Oi=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 bi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Ni({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 Li({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Pi(e,{addressSorter:t.addressSorter??vn,maxParallelDials:t.maxParallelDials??Ci,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(iu)]});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}=Ei(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??Ml}),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)}};function kw(r){return r[Symbol.asyncIterator]!=null}function Nw(...r){let e=[];for(let t of r)kw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=vi({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 Eo=Nw;var Ui=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 Eo(...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 Mi=globalThis.CustomEvent??Event;async function*Fl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=le(),a=le(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=le(),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 Mi("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new Mi("task-complete"))})}c=!0,o.dispatchEvent(new Mi("task-complete"))}catch(d){u=d,o.dispatchEvent(new Mi("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=le(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var Fi=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=Eo(...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=Oc(1024);for await(let s of Fl(async function*(){let i=Eo(...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 Vi=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,ue(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ue(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=wo([this.shutdownController.signal,e?.signal]);ue(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=le(),yield(await Rn(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,ue(1/0,this.walkController.signal);let e=wo([this.walkController.signal,this.shutdownController.signal]);ue(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=wt(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 Vl=32,Kl=64,Ki=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=wi.bind({ignoreUndefined:!0})({maxInboundStreams:Vl,maxOutboundStreams:Kl},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 Hl=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 Wd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Hl({name:e,metrics:t}):n=new Map,n}var Hi=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=Wd({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 $l=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=le(),this.haveNext=le()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=le(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=le(),await fr(this.readNext.promise,t?.signal,t)}};function jd(){return new $l}var $i=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 Xd(r,e){let t=jd();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 $i("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 qi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Gi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function xo(r,e={}){let t=Xd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??ct,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 qi("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Gi("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new zi("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 Lw=L(`
|
|
8
|
+
`);async function Mr(r,e,t){await r.write(e,t)}async function Zd(r,e,t){await r.writeV(e,t)}async function Dw(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==Lw[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 Dw(r,e);return F(t.subarray())}async function vo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Pw(r,e[0],t);let n=xo(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
9
|
`),i=L(`${o}
|
|
10
|
-
`);await
|
|
11
|
-
`),t),t.log.trace("select: reading protocol response");let u=await
|
|
12
|
-
`;yield new
|
|
13
|
-
`),
|
|
10
|
+
`);await Zd(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 Mr(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 Pw(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=le(),c=!1,u=!1,f=le(),l=!1,p=!1,h=le(),d=xo({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
14
|
`),L(`${e}
|
|
15
|
-
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',
|
|
16
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',
|
|
17
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new
|
|
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 Yi(r){return r[Symbol.asyncIterator]!=null}var Wi=r=>{let e=de(r),t=ke(e);return Le(r,t),Wi.bytes=e,t};Wi.bytes=0;function ji(r,e){e=e??{};let t=e.lengthEncoder??Wi;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Yi(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}ji.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Wi;return new we(t(r.byteLength),r)};var Xi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Qi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_o=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ow=8,Uw=1024*1024*4,Fr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fr||(Fr={}));var Wl=r=>{let e=ct(r);return Wl.bytes=de(e),e};Wl.bytes=0;function Yl(r,e){let t=new we,n=Fr.LENGTH,o=-1,s=e?.lengthDecoder??Wl,i=e?.maxLengthLength??Ow,a=e?.maxDataLength??Uw;function*c(){for(;t.byteLength>0;){if(n===Fr.LENGTH)try{if(o=s(t),o<0)throw new Xi("Invalid message length");if(o>a)throw new Zi("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Fr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Qi("Message length length too long");break}throw u}if(n===Fr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Fr.LENGTH}}}return Yi(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new _o("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new _o("Unexpected end of input")}()}Yl.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 Yl(n,{...e??{},onLength:s=>{t=s}})};async function Ao(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=xo(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 Mr(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 Mr(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=>ji.single(L(`${i}
|
|
18
18
|
`))),L(`
|
|
19
|
-
`));t.log.trace('handle: respond with "%s" for %s',e,o),await
|
|
20
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var Bw=500,Fl=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";[Xl]=!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(Bw);fe(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 Hd(r){return new Fl(r)}var Tw=3e4;function Cw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return kl}function kw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==C.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Nl}function $d(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var zi=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}`,C.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",C.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",Io))};u.addEventListener("abort",f,{once:!0}),fe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",C.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 de("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",C.ERR_INVALID_MULTIADDR);let h=be(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new de("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=be(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",C.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:y,protocol:g}=await vo(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let w=Cw(g,this.components.registrar);if($d(g,"inbound",l)===w){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${w}`,C.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=y.source,d.sink=y.sink,d.protocol=g,y.closeWrite!=null&&(d.closeWrite=y.closeWrite),y.closeRead!=null&&(d.closeRead=y.closeRead),y.close!=null&&(d.close=y.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",C.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let y=await u.newStream();l.log.trace("started new stream %s for protocols %s",y.id,d);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(Tw);fe(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:w}=await xo(y,d,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",w);let b=kw(w,this.components.registrar,m),x=$d(w,"outbound",l);if(x>=b){let v=new E(`Too many outbound protocol streams for protocol "${w}" - ${x}/${b}`,C.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[w]}),y.source=g.source,y.sink=g.sink,y.protocol=w,g.closeWrite!=null&&(y.closeWrite=g.closeWrite),g.closeRead!=null&&(y.closeRead=g.closeRead),g.close!=null&&(y.close=g.close),this.components.metrics?.trackProtocolStream(y,l),y}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new E(String(g),C.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",C.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Hd({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 vo(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,C.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 xo(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,C.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 xo(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),C.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 vo(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),C.ERR_MUXER_UNAVAILABLE)}}};var qd="1.8.2-f30e2ee8d",zd="libp2p";var Vl=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 Zi(a.type,{detail:a.detail}));return c||u},fe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ms(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=nd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:zd,version:qd},logger:this.logger,events:t,datastore:e.datastore??new ri,connectionGater:ad(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new ei(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 zi(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 Fi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Li(this.components,e.connectionManager)),this.configureComponent("registrar",new Mi(this.components)),this.configureComponent("addressManager",new ni(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 Oi(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 Di(this.components,{routers:i})),this.configureComponent("randomWalk",new Ui(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[Yi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Yi])),u[ji]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ji])),u[Wi]!=null&&(this.log("registering service %s for peer discovery",a),u[Wi].addEventListener?.("peer",f=>{this.#e(f)}))}od(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 Ft;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",C.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",C.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={}){cr(e)&&(e=be(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!==C.ERR_NOT_FOUND)throw s}let n=Ie([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return Jn(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(C.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Gd(r={}){let e=r.peerId??=await xh();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await eo(e.privateKey),new Vl(await kd(r))}async function Lw(r={}){let e=await Gd(r);return r.start!==!1&&await e.start(),e}return ip(Dw);})();
|
|
19
|
+
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Mr(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 Mr(n,L(`na
|
|
20
|
+
`),t),t.log('handle: responded with "na" for "%s"',o)}}var Fw=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";[su]=!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(Fw);ue(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 Jd(r){return new jl(r)}var Vw=3e4;function Kw(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 Vl}function Hw(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??Kl}function ep(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ji=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",Co))};u.addEventListener("abort",f,{once:!0}),ue(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 Ao(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let y=Kw(g,this.components.registrar);if(ep(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(Vw);ue(1/0,A),m={...m,signal:A}}w.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:y}=await vo(w,d,{...m,log:w.log,yieldBytes:!0});w.log("selected protocol %s",y);let b=Hw(y,this.components.registrar,m),x=ep(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=Jd({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 Ao(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 vo(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 vo(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 Ao(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 tp="1.8.3-0edbfe7af",rp="libp2p";var Xl=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 oa(a.type,{detail:a.detail}));return c||u},ue(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ks(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=pd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:rp,version:tp},logger:this.logger,events:t,datastore:e.datastore??new si,connectionGater:wd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new ni(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 Ji(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 Hi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Oi(this.components,e.connectionManager)),this.configureComponent("registrar",new Ki(this.components)),this.configureComponent("addressManager",new ii(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 Fi(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 Ui(this.components,{routers:i})),this.configureComponent("randomWalk",new Vi(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[ta]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ta])),u[na]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[na])),u[ra]!=null&&(this.log("registering service %s for peer discovery",a),u[ra].addEventListener?.("peer",f=>{this.#e(f)}))}md(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 eo(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 np(r={}){let e=r.peerId??=await kh();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await to(e.privateKey),new Xl(await Hd(r))}async function qw(r={}){let e=await np(r);return r.start!==!1&&await e.start(),e}return gp(zw);})();
|
|
21
21
|
/*! Bundled license information:
|
|
22
22
|
|
|
23
23
|
pvtsutils/build/index.js:
|