libp2p 0.46.3-a1fbb7e2 → 0.46.3-a31b420f

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 CHANGED
@@ -34,7 +34,7 @@
34
34
  END,
35
35
  expire = ${s}
36
36
  RETURNING points, expire;`,values:[e,r,o,Date.now()]})}_get(e){return this.tableCreated?new Promise((r,n)=>{this._query({name:"rlflx-get",text:`
37
- SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),r(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}};Iy.exports=Pl});var Cy=O(()=>{});var By=O(($6,Ty)=>{Ty.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Py=O((H6,Ly)=>{var O_=By(),Dl=vt();Ly.exports=class{constructor(){this._storage={}}incrby(e,r,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+r,new Dl(0,i,this._storage[e].value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new O_(r,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new Dl(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let r=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new Dl(0,r,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var kl=O((G6,Ny)=>{var M_=So(),U_=Py(),Dy=vt(),Nl=class extends M_{constructor(e={}){super(e),this._memoryStorage=new U_}consume(e,r=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(i,u,c)}else i(c)})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,r,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-r,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,r){let n=r*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,r),Promise.resolve(new Dy(0,n===0?-1:n,i))}set(e,r,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new Dy(0,i===0?-1:i,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Ny.exports=Nl});var qy=O((Y6,Fy)=>{var ky=Cy(),K_=Vi(),F_=So(),My=kl(),q_=vt(),Tt="rate_limiter_flexible",Li=null,Oy=function(t,e,r,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},t.send({channel:Tt,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:r,data:i})},Uy=function(t){setTimeout(()=>{this._initiated?process.send(t):typeof this._promises[t.promiseId]<"u"&&Uy.call(this,t)},30)},Ti=function(t,e,r,n,i){let o={channel:Tt,keyPrefix:this.keyPrefix,func:t,promiseId:e,data:{key:r,arg:n,opts:i}};this._initiated?process.send(o):Uy.call(this,o)},Ky=function(t,e){if(!e||e.channel!==Tt||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let r;switch(e.func){case"consume":r=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":r=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":r=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":r=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":r=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":r=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}r&&r.then(n=>{Oy(t,e,"resolve",n)}).catch(n=>{Oy(t,e,"reject",n)})},V_=function(t){if(!t||t.channel!==Tt||t.keyPrefix!==this.keyPrefix)return!1;if(this._promises[t.promiseId]){clearTimeout(this._promises[t.promiseId].timeoutId);let e;switch(t.data===null||t.data===!0||t.data===!1?e=t.data:e=new q_(t.data.remainingPoints,t.data.msBeforeNext,t.data.consumedPoints,t.data.isFirstInDuration),t.type){case"resolve":this._promises[t.promiseId].resolve(e);break;case"reject":this._promises[t.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${t.type}'`)}delete this._promises[t.promiseId]}},$_=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},Bi=function(t,e){let r=process.hrtime(),n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=K_.randomBytes(12).toString("base64")),this._promises[n]={resolve:t,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},Ol=class{constructor(){if(Li)return Li;this._rateLimiters={},ky.setMaxListeners(0),ky.on("message",(e,r)=>{r&&r.channel===Tt&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new My(r.opts)),e.send({channel:Tt,type:"init",keyPrefix:r.opts.keyPrefix})):Ky.call(this,e,r)}),Li=this}},Ml=class{constructor(e){if(Li)return Li;this._rateLimiters={},e.launchBus((r,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===Tt&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new My(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:Tt,channel:Tt,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=Tt,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};Ky.call(this,s,o)}})}),Li=this}},Ul=class extends F_{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===Tt&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:V_.call(this,r)}),process.send({channel:Tt,type:"init",opts:$_.call(this)}),this._promises={}}consume(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"consume",s,e,r,n)})}penalty(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"penalty",s,e,r,n)})}reward(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"reward",s,e,r,n)})}block(e,r,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"block",s,e,r,n)})}get(e,r={}){return new Promise((n,i)=>{let o=Bi.call(this,n,i);Ti.call(this,"get",o,e,r)})}delete(e,r={}){return new Promise((n,i)=>{let o=Bi.call(this,n,i);Ti.call(this,"delete",o,e,r)})}};Fy.exports={RateLimiterClusterMaster:Ol,RateLimiterClusterMasterPM2:Ml,RateLimiterCluster:Ul}});var $y=O((W6,Vy)=>{var z_=Ci(),H_=vt(),Kl=class extends z_{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,r,n){let i=new H_;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===r,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,r,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,r,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,r,(l,f)=>{l||f===!1?this.client.add(e,r,u,(h,p)=>{if(h||!p)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let d=Object.assign({},o);d.attemptNumber=d.attemptNumber?d.attemptNumber+1:1,this._upsert(e,r,n,i,d).then(m=>s(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let d={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};s(d)})}):this.client.get(`${e}_expire`,(h,p)=>{if(h)a(h);else{let d=p===!1?0:p,m={consumedPoints:f,msBeforeNext:d>=0?Math.max(d-c,0):-1};s(m)}})})})}_get(e){return new Promise((r,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};r(l)}}):r(null)})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?r(o):this.client.del(`${e}_expire`,s=>{s?n(s):r(o)})})})}};Vy.exports=Kl});var Gy=O((X6,Hy)=>{var zy=vt();Hy.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new zy(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new zy(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,r=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,r):(this.runActionAnyway&&this.limiter.consume(e,r).catch(()=>{}),n)}block(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,r):(this.runActionAnyway&&this.limiter.block(e,r).catch(()=>{}),n)}penalty(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,r):(this.runActionAnyway&&this.limiter.penalty(e,r).catch(()=>{}),n)}reward(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,r):(this.runActionAnyway&&this.limiter.reward(e,r).catch(()=>{}),n)}get(e){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(e):r}delete(e){return this.limiter.delete(e)}}});var Wy=O((j6,Yy)=>{var G_=So();Yy.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(r=>{if(!(r instanceof G_))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,r=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,r).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u<s.length;u++)c&&s[u].rejected===!0?a[this._limiters[u].keyPrefix]=s[u].rej:c||(a[this._limiters[u].keyPrefix]=s[u]);c?i(a):n(a)})})}}});var Xy=O((e5,Qy)=>{Qy.exports=class extends Error{constructor(e,r){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,r&&(this.extra=r)}}});var eg=O((r5,Jy)=>{var Zy=Xy(),jy=4294967295,Fl="limiter";Jy.exports=class{constructor(e,r={maxQueueSize:jy}){this._queueLimiters={KEY_DEFAULT:new da(e,r)},this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(e=Fl){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,r=Fl){return this._queueLimiters[r]||(this._queueLimiters[r]=new da(this._limiterFlexible,{key:r,maxQueueSize:this._maxQueueSize})),this._queueLimiters[r].removeTokens(e)}};var da=class{constructor(e,r={maxQueueSize:jy,key:Fl}){this._key=r.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let r=this;return new Promise((n,i)=>{if(e>r._limiterFlexible.points){i(new Zy(`Requested tokens ${e} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,i,e):r._limiterFlexible.consume(r._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(r._queueRequest.call(r,n,i,e),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),o.msBeforeNext)))})})}_queueRequest(e,r,n){let i=this;i._queue.length<i._maxQueueSize?i._queue.push({resolve:e,reject:r,tokens:n}):r(new Zy(`Number of requests reached it's maximum ${i._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let r=e._queue.shift();e._limiterFlexible.consume(e._key,r.tokens).then(n=>{r.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(r.reject(n),e._processFIFO.call(e)):(e._queue.unshift(r),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var rg=O((i5,tg)=>{var ql=vt();tg.exports=class{constructor(e,r){this._rateLimiter=e,this._burstLimiter=r}_combineRes(e,r){return e?new ql(e.remainingPoints,Math.min(e.msBeforeNext,r?r.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,r=1,n={}){return this._rateLimiter.consume(e,r,n).catch(i=>i instanceof ql?this._burstLimiter.consume(e,r,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof ql?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}}});var ig=O((o5,ng)=>{var Y_=wy(),W_=_y(),Q_=Sy(),X_=Ry(),{RateLimiterClusterMaster:Z_,RateLimiterClusterMasterPM2:j_,RateLimiterCluster:J_}=qy(),eA=kl(),tA=$y(),rA=Gy(),nA=Wy(),iA=eg(),oA=rg(),sA=vt();ng.exports={RateLimiterRedis:Y_,RateLimiterMongo:W_,RateLimiterMySQL:Q_,RateLimiterPostgres:X_,RateLimiterMemory:eA,RateLimiterMemcache:tA,RateLimiterClusterMaster:Z_,RateLimiterClusterMasterPM2:j_,RateLimiterCluster:J_,RLWrapperBlackAndWhite:rA,RateLimiterUnion:nA,RateLimiterQueue:iA,BurstyRateLimiter:oA,RateLimiterRes:sA}});var KA={};He(KA,{createLibp2p:()=>UA});var vg=J($n(),1);var M8=J(qi(),1),U8=J(H0(),1);var Wn=class t extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=t.code,this.type=t.type}static code="ABORT_ERR";static type="aborted"},E=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var Ts=J(ye(),1);function cn(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var uc={};He(uc,{identity:()=>b2});function p2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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,x=d.length;g!==x&&d[g]===0;)g++,m++;for(var w=(x-g)*l+1>>>0,C=new Uint8Array(w);g!==x;){for(var _=d[g],A=0,P=w-1;(_!==0||A<y)&&P!==-1;P--,A++)_+=256*C[P]>>>0,C[P]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}for(var D=w-y;D!==w&&C[D]===0;)D++;for(var W=c.repeat(m);D<w;++D)W+=t.charAt(C[D]);return W}function h(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 x=(d.length-m)*u+1>>>0,w=new Uint8Array(x);d[m];){var C=r[d.charCodeAt(m)];if(C===255)return;for(var _=0,A=x-1;(C!==0||_<g)&&A!==-1;A--,_++)C+=a*w[A]>>>0,w[A]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=_,m++}if(d[m]!==" "){for(var P=x-g;P!==x&&w[P]===0;)P++;for(var D=new Uint8Array(y+(x-P)),W=y;P!==x;)D[W++]=w[P++];return D}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var m2=p2,y2=m2,G0=y2;var yS=new Uint8Array(0);var Y0=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},pr=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var W0=t=>new TextEncoder().encode(t),Q0=t=>new TextDecoder().decode(t);var oc=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},sc=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.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 Z0(this,e)}},ac=class{constructor(e){this.decoders=e}or(e){return Z0(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Z0=(t,e)=>new ac({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),cc=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new oc(e,r,n),this.decoder=new sc(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Qn=({name:t,prefix:e,encode:r,decode:n})=>new cc(t,e,r,n),Dr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=G0(r,e);return Qn({prefix:t,name:e,encode:n,decode:o=>pr(i(o))})},g2=(t,e,r,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},x2=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>r;)s-=r,o+=e[i&a>>s];if(s&&(o+=e[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Ne=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Qn({prefix:e,name:t,encode(i){return x2(i,n,r)},decode(i){return g2(i,n,r,t)}});var b2=Qn({prefix:"\0",name:"identity",encode:t=>Q0(t),decode:t=>W0(t)});var lc={};He(lc,{base2:()=>w2});var w2=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fc={};He(fc,{base8:()=>E2});var E2=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hc={};He(hc,{base10:()=>v2});var v2=Dr({prefix:"9",name:"base10",alphabet:"0123456789"});var dc={};He(dc,{base16:()=>_2,base16upper:()=>A2});var _2=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A2=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pc={};He(pc,{base32:()=>mt,base32hex:()=>C2,base32hexpad:()=>B2,base32hexpadupper:()=>L2,base32hexupper:()=>T2,base32pad:()=>I2,base32padupper:()=>R2,base32upper:()=>S2,base32z:()=>P2});var mt=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),S2=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),I2=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R2=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),C2=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),T2=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),B2=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L2=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),P2=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mc={};He(mc,{base36:()=>D2,base36upper:()=>N2});var D2=Dr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),N2=Dr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yc={};He(yc,{base58btc:()=>Oe,base58flickr:()=>k2});var Oe=Dr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),k2=Dr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var gc={};He(gc,{base64:()=>un,base64pad:()=>O2,base64url:()=>M2,base64urlpad:()=>U2});var un=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O2=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),M2=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U2=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xc={};He(xc,{base256emoji:()=>$2});var j0=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}"),K2=j0.reduce((t,e,r)=>(t[r]=e,t),[]),F2=j0.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function q2(t){return t.reduce((e,r)=>(e+=K2[r],e),"")}function V2(t){let e=[];for(let r of t){let n=F2[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var $2=Qn({prefix:"\u{1F680}",name:"base256emoji",encode:q2,decode:V2});var vc={};He(vc,{sha256:()=>et,sha512:()=>cb});var z2=th,J0=128,H2=127,G2=~H2,Y2=Math.pow(2,31);function th(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Y2;)e[r++]=t&255|J0,t/=128;for(;t&G2;)e[r++]=t&255|J0,t>>>=7;return e[r]=t|0,th.bytes=r-n+1,e}var W2=bc,Q2=128,eh=127;function bc(t,n){var r=0,n=n||0,i=0,o=n,s,a=t.length;do{if(o>=a)throw bc.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&eh)<<i:(s&eh)*Math.pow(2,i),i+=7}while(s>=Q2);return bc.bytes=o-n,r}var X2=Math.pow(2,7),Z2=Math.pow(2,14),j2=Math.pow(2,21),J2=Math.pow(2,28),eb=Math.pow(2,35),tb=Math.pow(2,42),rb=Math.pow(2,49),nb=Math.pow(2,56),ib=Math.pow(2,63),ob=function(t){return t<X2?1:t<Z2?2:t<j2?3:t<J2?4:t<eb?5:t<tb?6:t<rb?7:t<nb?8:t<ib?9:10},sb={encode:z2,decode:W2,encodingLength:ob},ab=sb,Hi=ab;var Gi=(t,e=0)=>[Hi.decode(t,e),Hi.decode.bytes],Xn=(t,e,r=0)=>(Hi.encode(t,e,r),e),Zn=t=>Hi.encodingLength(t);var Jt=(t,e)=>{let r=e.byteLength,n=Zn(t),i=n+Zn(r),o=new Uint8Array(i+r);return Xn(t,o,0),Xn(r,o,n),o.set(e,i),new jn(t,r,e,o)},ln=t=>{let e=pr(t),[r,n]=Gi(e),[i,o]=Gi(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new jn(r,i,s,e)},rh=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Y0(t.bytes,r.bytes)}},jn=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var Ec=({name:t,code:e,encode:r})=>new wc(t,e,r),wc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Jt(this.code,r):r.then(n=>Jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};var ih=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),et=Ec({name:"sha2-256",code:18,encode:ih("SHA-256")}),cb=Ec({name:"sha2-512",code:19,encode:ih("SHA-512")});var _c={};He(_c,{identity:()=>Nr});var oh=0,ub="identity",sh=pr,lb=t=>Jt(oh,sh(t)),Nr={code:oh,name:ub,encode:sh,digest:lb};var MS=new TextEncoder,US=new TextDecoder;var ah=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return pb(r,Ac(t),e||Oe.encoder);default:return mb(r,Ac(t),e||mt.encoder)}};var ch=new WeakMap,Ac=t=>{let e=ch.get(t);if(e==null){let r=new Map;return ch.set(t,r),r}return e},Pt=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:r}=this;if(e!==Yi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yb)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Jt(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&rh(e.multihash,n.multihash)}toString(e){return ah(this,e)}toJSON(){return{"/":ah(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s||uh(n,i,o.bytes))}else if(r[gb]===!0){let{version:n,multihash:i,code:o}=r,s=ln(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="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(r!==Yi)throw new Error(`Version 0 CID must use dag-pb (code: ${Yi}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=uh(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Yi,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=pr(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new jn(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=Gi(e.subarray(r));return r+=h,f},i=n(),o=Yi;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,i]=db(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ac(o).set(n,e),o}},db=(t,e)=>{switch(t[0]){case"Q":{let r=e||Oe;return[Oe.prefix,r.decode(`${Oe.prefix}${t}`)]}case Oe.prefix:{let r=e||Oe;return[Oe.prefix,r.decode(t)]}case mt.prefix:{let r=e||mt;return[mt.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},pb=(t,e,r)=>{let{prefix:n}=r;if(n!==Oe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i},mb=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i},Yi=112,yb=18,uh=(t,e,r)=>{let n=Zn(t),i=n+Zn(e),o=new Uint8Array(i+r.byteLength);return Xn(t,o,0),Xn(e,o,n),o.set(r,i),o},gb=Symbol.for("@ipld/js-cid/CID");var kr={...uc,...lc,...fc,...hc,...dc,...pc,...mc,...yc,...gc,...xc},WS={...vc,..._c};function mr(t=0){return globalThis.Buffer?.alloc!=null?cn(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function Dt(t=0){return globalThis.Buffer?.allocUnsafe!=null?cn(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var lh=fh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Sc=fh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Dt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),xb={utf8:lh,"utf-8":lh,hex:kr.base16,latin1:Sc,ascii:Sc,binary:Sc,...kr},is=xb;function Y(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?cn(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var au={};He(au,{Ed25519PrivateKey:()=>xn,Ed25519PublicKey:()=>Ji,generateKeyPair:()=>Kw,generateKeyPairFromSeed:()=>Id,unmarshalEd25519PrivateKey:()=>Mw,unmarshalEd25519PublicKey:()=>Uw});function Le(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ic(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function bb(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}function hh(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function wb(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ic(t.outputLen),Ic(t.blockLen)}function Eb(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vb(t,e){hh(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var _b={number:Ic,bool:bb,bytes:hh,hash:wb,exists:Eb,output:vb},yr=_b;var os=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var dh=t=>t instanceof Uint8Array;var ss=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Nt=(t,e)=>t<<32-e|t>>>e,Ab=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ab)throw new Error("Non little-endian hardware is not supported");var cI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rc(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Wi(t){if(typeof t=="string"&&(t=Rc(t)),!dh(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function as(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;return t.forEach(n=>{if(!dh(n))throw new Error("Uint8Array expected");e.set(n,r),r+=n.length}),e}var Jn=class{clone(){return this._cloneInto()}};function Or(t){let e=n=>t().update(Wi(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function hn(t=32){if(os&&typeof os.getRandomValues=="function")return os.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Sb(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;t.setUint32(e+c,s,n),t.setUint32(e+u,a,n)}var ei=class extends Jn{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ss(this.buffer)}update(e){yr.exists(this);let{view:r,buffer:n,blockLen:i}=this;e=Wi(e);let o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=ss(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){yr.exists(this),yr.output(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;Sb(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=ss(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.length=i,e.pos=a,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var cs=BigInt(4294967295),Cc=BigInt(32);function ph(t,e=!1){return e?{h:Number(t&cs),l:Number(t>>Cc&cs)}:{h:Number(t>>Cc&cs)|0,l:Number(t&cs)|0}}function Ib(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=ph(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var Rb=(t,e)=>BigInt(t>>>0)<<Cc|BigInt(e>>>0),Cb=(t,e,r)=>t>>>r,Tb=(t,e,r)=>t<<32-r|e>>>r,Bb=(t,e,r)=>t>>>r|e<<32-r,Lb=(t,e,r)=>t<<32-r|e>>>r,Pb=(t,e,r)=>t<<64-r|e>>>r-32,Db=(t,e,r)=>t>>>r-32|e<<64-r,Nb=(t,e)=>e,kb=(t,e)=>t,Ob=(t,e,r)=>t<<r|e>>>32-r,Mb=(t,e,r)=>e<<r|t>>>32-r,Ub=(t,e,r)=>e<<r-32|t>>>64-r,Kb=(t,e,r)=>t<<r-32|e>>>64-r;function Fb(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var qb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Vb=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,$b=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),zb=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,Hb=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Gb=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0,Yb={fromBig:ph,split:Ib,toBig:Rb,shrSH:Cb,shrSL:Tb,rotrSH:Bb,rotrSL:Lb,rotrBH:Pb,rotrBL:Db,rotr32H:Nb,rotr32L:kb,rotlSH:Ob,rotlSL:Mb,rotlBH:Ub,rotlBL:Kb,add:Fb,add3L:qb,add3H:Vb,add4L:$b,add4H:zb,add5H:Gb,add5L:Hb},j=Yb;var[Wb,Qb]=j.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(t=>BigInt(t))),Mr=new Uint32Array(80),Ur=new Uint32Array(80),ti=class extends ei{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:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:p,Gl:d,Hh:m,Hl:y}=this;return[e,r,n,i,o,s,a,c,u,l,f,h,p,d,m,y]}set(e,r,n,i,o,s,a,c,u,l,f,h,p,d,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=d|0,this.Hh=m|0,this.Hl=y|0}process(e,r){for(let w=0;w<16;w++,r+=4)Mr[w]=e.getUint32(r),Ur[w]=e.getUint32(r+=4);for(let w=16;w<80;w++){let C=Mr[w-15]|0,_=Ur[w-15]|0,A=j.rotrSH(C,_,1)^j.rotrSH(C,_,8)^j.shrSH(C,_,7),P=j.rotrSL(C,_,1)^j.rotrSL(C,_,8)^j.shrSL(C,_,7),D=Mr[w-2]|0,W=Ur[w-2]|0,Q=j.rotrSH(D,W,19)^j.rotrBH(D,W,61)^j.shrSH(D,W,6),H=j.rotrSL(D,W,19)^j.rotrBL(D,W,61)^j.shrSL(D,W,6),ne=j.add4L(P,H,Ur[w-7],Ur[w-16]),ge=j.add4H(ne,A,Q,Mr[w-7],Mr[w-16]);Mr[w]=ge|0,Ur[w]=ne|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:p,Fl:d,Gh:m,Gl:y,Hh:g,Hl:x}=this;for(let w=0;w<80;w++){let C=j.rotrSH(f,h,14)^j.rotrSH(f,h,18)^j.rotrBH(f,h,41),_=j.rotrSL(f,h,14)^j.rotrSL(f,h,18)^j.rotrBL(f,h,41),A=f&p^~f&m,P=h&d^~h&y,D=j.add5L(x,_,P,Qb[w],Ur[w]),W=j.add5H(D,g,C,A,Wb[w],Mr[w]),Q=D|0,H=j.rotrSH(n,i,28)^j.rotrBH(n,i,34)^j.rotrBH(n,i,39),ne=j.rotrSL(n,i,28)^j.rotrBL(n,i,34)^j.rotrBL(n,i,39),ge=n&o^n&a^o&a,Ze=i&s^i&c^s&c;g=m|0,x=y|0,m=p|0,y=d|0,p=f|0,d=h|0,{h:f,l:h}=j.add(u|0,l|0,W|0,Q|0),u=a|0,l=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let T=j.add3L(Q,ne,Ze);n=j.add3H(T,W,H,ge),i=T|0}({h:n,l:i}=j.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=j.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=j.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=j.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:d}=j.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:m,l:y}=j.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:g,l:x}=j.add(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,i,o,s,a,c,u,l,f,h,p,d,m,y,g,x)}roundClean(){Mr.fill(0),Ur.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)}},Tc=class extends ti{constructor(){super(),this.Ah=-1942145080,this.Al=424955298,this.Bh=1944164710,this.Bl=-1982016298,this.Ch=502970286,this.Cl=855612546,this.Dh=1738396948,this.Dl=1479516111,this.Eh=258812777,this.El=2077511080,this.Fh=2011393907,this.Fl=79989058,this.Gh=1067287976,this.Gl=1780299464,this.Hh=286451373,this.Hl=-1848208735,this.outputLen=28}},Bc=class extends ti{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}},Lc=class extends ti{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}},Pc=Or(()=>new ti),gI=Or(()=>new Tc),xI=Or(()=>new Bc),bI=Or(()=>new Lc);var fs={};He(fs,{bitGet:()=>ew,bitLen:()=>Jb,bitMask:()=>Qi,bitSet:()=>tw,bytesToHex:()=>er,bytesToNumberBE:()=>kt,bytesToNumberLE:()=>tr,concatBytes:()=>Ot,createHmacDrbg:()=>kc,ensureBytes:()=>ve,equalBytes:()=>xh,hexToBytes:()=>dn,hexToNumber:()=>Nc,numberToBytesBE:()=>gr,numberToBytesLE:()=>Kr,numberToHexUnpadded:()=>gh,numberToVarBytesBE:()=>jb,utf8ToBytes:()=>bh,validateObject:()=>It});var yh=BigInt(0),us=BigInt(1),Xb=BigInt(2),ls=t=>t instanceof Uint8Array,Zb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function er(t){if(!ls(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Zb[t[r]];return e}function gh(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Nc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function dn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(e/2);for(let n=0;n<r.length;n++){let i=n*2,o=t.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");r[n]=s}return r}function kt(t){return Nc(er(t))}function tr(t){if(!ls(t))throw new Error("Uint8Array expected");return Nc(er(Uint8Array.from(t).reverse()))}function gr(t,e){return dn(t.toString(16).padStart(e*2,"0"))}function Kr(t,e){return gr(t,e).reverse()}function jb(t){return dn(gh(t))}function ve(t,e,r){let n;if(typeof e=="string")try{n=dn(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(ls(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function Ot(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;return t.forEach(n=>{if(!ls(n))throw new Error("Uint8Array expected");e.set(n,r),r+=n.length}),e}function xh(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function bh(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Jb(t){let e;for(e=0;t>yh;t>>=us,e+=1);return e}function ew(t,e){return t>>BigInt(e)&us}var tw=(t,e,r)=>t|(r?us:yh)<<BigInt(e),Qi=t=>(Xb<<BigInt(t-1))-us,Dc=t=>new Uint8Array(t),mh=t=>Uint8Array.from(t);function kc(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=Dc(t),i=Dc(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...f)=>r(i,n,...f),c=(f=Dc())=>{i=a(mh([0]),f),n=a(),f.length!==0&&(i=a(mh([1]),f),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=a();let p=n.slice();h.push(p),f+=n.length}return Ot(...h)};return(f,h)=>{s(),c(f);let p;for(;!(p=h(u()));)c();return s(),p}}var rw={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function It(t,e,r={}){let n=(i,o,s)=>{let a=rw[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);let c=t[i];if(!(s&&c===void 0)&&!a(c,t))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var $e=BigInt(0),Re=BigInt(1),pn=BigInt(2),nw=BigInt(3),Oc=BigInt(4),wh=BigInt(5),Eh=BigInt(8),iw=BigInt(9),ow=BigInt(16);function de(t,e){let r=t%e;return r>=$e?r:e+r}function vh(t,e,r){if(r<=$e||e<$e)throw new Error("Expected power/modulo > 0");if(r===Re)return $e;let n=Re;for(;e>$e;)e&Re&&(n=n*t%r),t=t*t%r,e>>=Re;return n}function Ce(t,e,r){let n=t;for(;e-- >$e;)n*=n,n%=r;return n}function hs(t,e){if(t===$e||e<=$e)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=de(t,e),n=e,i=$e,o=Re,s=Re,a=$e;for(;r!==$e;){let u=n/r,l=n%r,f=i-s*u,h=o-a*u;n=r,r=l,i=s,o=a,s=f,a=h}if(n!==Re)throw new Error("invert: does not exist");return de(i,e)}function sw(t){let e=(t-Re)/pn,r,n,i;for(r=t-Re,n=0;r%pn===$e;r/=pn,n++);for(i=pn;i<t&&vh(i,e,t)!==t-Re;i++);if(n===1){let s=(t+Re)/Oc;return function(c,u){let l=c.pow(u,s);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let o=(r+Re)/pn;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,i),r),f=a.pow(c,o),h=a.pow(c,r);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let p=1;for(let m=a.sqr(h);p<u&&!a.eql(m,a.ONE);p++)m=a.sqr(m);let d=a.pow(l,Re<<BigInt(u-p-1));l=a.sqr(d),f=a.mul(f,d),h=a.mul(h,l),u=p}return f}}function aw(t){if(t%Oc===nw){let e=(t+Re)/Oc;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%Eh===wh){let e=(t-wh)/Eh;return function(n,i){let o=n.mul(i,pn),s=n.pow(o,e),a=n.mul(i,s),c=n.mul(n.mul(a,pn),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%ow,sw(t)}var _h=(t,e)=>(de(t,e)&Re)===Re,cw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mc(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=cw.reduce((n,i)=>(n[i]="function",n),e);return It(t,r)}function uw(t,e,r){if(r<$e)throw new Error("Expected power > 0");if(r===$e)return t.ONE;if(r===Re)return e;let n=t.ONE,i=e;for(;r>$e;)r&Re&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Re;return n}function lw(t,e){let r=new Array(e.length),n=e.reduce((o,s,a)=>t.is0(s)?o:(r[a]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,a)=>t.is0(s)?o:(r[a]=t.mul(o,r[a]),t.mul(o,s)),i),r}function ds(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ps(t,e,r=!1,n={}){if(t<=$e)throw new Error(`Expected Fp ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=ds(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=aw(t),a=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Qi(i),ZERO:$e,ONE:Re,create:c=>de(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return $e<=c&&c<t},is0:c=>c===$e,isOdd:c=>(c&Re)===Re,neg:c=>de(-c,t),eql:(c,u)=>c===u,sqr:c=>de(c*c,t),add:(c,u)=>de(c+u,t),sub:(c,u)=>de(c-u,t),mul:(c,u)=>de(c*u,t),pow:(c,u)=>uw(a,c,u),div:(c,u)=>de(c*hs(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>hs(c,t),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>lw(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Kr(c,o):gr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return r?tr(c):kt(c)}});return Object.freeze(a)}function Ah(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function Sh(t,e,r=!1){t=ve("privateHash",t);let n=t.length,i=ds(e).nByteLength+8;if(i<24||n<i||n>1024)throw new Error(`hashToPrivateScalar: expected ${i}-1024 bytes of input, got ${n}`);let o=r?tr(t):kt(t);return de(o,e-Re)+Re}var hw=BigInt(0),Uc=BigInt(1);function ms(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,a=i;for(;o>hw;)o&Uc&&(s=s.add(a)),a=a.double(),o>>=Uc;return s},precomputeWindow(i,o){let{windows:s,windowSize:a}=n(o),c=[],u=i,l=u;for(let f=0;f<s;f++){l=u,c.push(l);for(let h=1;h<a;h++)l=l.add(u),c.push(l);u=l.double()}return c},wNAF(i,o,s){let{windows:a,windowSize:c}=n(i),u=t.ZERO,l=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let d=0;d<a;d++){let m=d*c,y=Number(s&f);s>>=p,y>c&&(y-=h,s+=Uc);let g=m,x=m+Math.abs(y)-1,w=d%2!==0,C=y<0;y===0?l=l.add(r(w,o[g])):u=u.add(r(C,o[x]))}return{p:u,f:l}},wNAFCached(i,o,s,a){let c=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&o.set(i,a(u))),this.wNAF(c,u,s)}}}function Xi(t){return Mc(t.Fp),It(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ds(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}var Mt=BigInt(0),yt=BigInt(1),ys=BigInt(2),dw=BigInt(8),pw={zip215:!0};function mw(t){let e=Xi(t);return It(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function gs(t){let e=mw(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:a,h:c}=e,u=ys<<BigInt(a*8)-yt,l=r.create,f=e.uvRatio||((N,I)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(I))}}catch{return{isValid:!1,value:Mt}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,I,K)=>{if(I.length||K)throw new Error("Contexts/pre-hash are not supported");return N}),d=N=>typeof N=="bigint"&&Mt<N,m=(N,I)=>d(N)&&d(I)&&N<I,y=N=>N===Mt||m(N,u);function g(N,I){if(m(N,I))return N;throw new Error(`Expected valid scalar < ${I}, got ${typeof N} ${N}`)}function x(N){return N===Mt?N:g(N,n)}let w=new Map;function C(N){if(!(N instanceof _))throw new Error("ExtendedPoint expected")}class _{constructor(I,K,V,G){if(this.ex=I,this.ey=K,this.ez=V,this.et=G,!y(I))throw new Error("x required");if(!y(K))throw new Error("y required");if(!y(V))throw new Error("z required");if(!y(G))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(I){if(I instanceof _)throw new Error("extended point not allowed");let{x:K,y:V}=I||{};if(!y(K)||!y(V))throw new Error("invalid affine point");return new _(K,V,yt,l(K*V))}static normalizeZ(I){let K=r.invertBatch(I.map(V=>V.ez));return I.map((V,G)=>V.toAffine(K[G])).map(_.fromAffine)}_setWindowSize(I){this._WINDOW_SIZE=I,w.delete(this)}assertValidity(){let{a:I,d:K}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:V,ey:G,ez:te,et:oe}=this,me=l(V*V),se=l(G*G),fe=l(te*te),Fe=l(fe*fe),De=l(me*I),je=l(fe*l(De+se)),Je=l(Fe+l(K*l(me*se)));if(je!==Je)throw new Error("bad point: equation left != right (1)");let Ve=l(V*G),st=l(te*oe);if(Ve!==st)throw new Error("bad point: equation left != right (2)")}equals(I){C(I);let{ex:K,ey:V,ez:G}=this,{ex:te,ey:oe,ez:me}=I,se=l(K*me),fe=l(te*G),Fe=l(V*me),De=l(oe*G);return se===fe&&Fe===De}is0(){return this.equals(_.ZERO)}negate(){return new _(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:I}=e,{ex:K,ey:V,ez:G}=this,te=l(K*K),oe=l(V*V),me=l(ys*l(G*G)),se=l(I*te),fe=K+V,Fe=l(l(fe*fe)-te-oe),De=se+oe,je=De-me,Je=se-oe,Ve=l(Fe*je),st=l(De*Je),lr=l(Fe*Je),tn=l(je*De);return new _(Ve,st,tn,lr)}add(I){C(I);let{a:K,d:V}=e,{ex:G,ey:te,ez:oe,et:me}=this,{ex:se,ey:fe,ez:Fe,et:De}=I;if(K===BigInt(-1)){let df=l((te-G)*(fe+se)),pf=l((te+G)*(fe-se)),ka=l(pf-df);if(ka===Mt)return this.double();let mf=l(oe*ys*De),yf=l(me*ys*Fe),gf=yf+mf,xf=pf+df,bf=yf-mf,Cg=l(gf*ka),Tg=l(xf*bf),Bg=l(gf*bf),Lg=l(ka*xf);return new _(Cg,Tg,Lg,Bg)}let je=l(G*se),Je=l(te*fe),Ve=l(me*V*De),st=l(oe*Fe),lr=l((G+te)*(se+fe)-je-Je),tn=st-Ve,Mi=st+Ve,hf=l(Je-K*je),Ag=l(lr*tn),Sg=l(Mi*hf),Ig=l(lr*hf),Rg=l(tn*Mi);return new _(Ag,Sg,Rg,Ig)}subtract(I){return this.add(I.negate())}wNAF(I){return D.wNAFCached(this,w,I,_.normalizeZ)}multiply(I){let{p:K,f:V}=this.wNAF(g(I,n));return _.normalizeZ([K,V])[0]}multiplyUnsafe(I){let K=x(I);return K===Mt?P:this.equals(P)||K===yt?this:this.equals(A)?this.wNAF(K).p:D.unsafeLadder(this,K)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(I){let{ex:K,ey:V,ez:G}=this,te=this.is0();I==null&&(I=te?dw:r.inv(G));let oe=l(K*I),me=l(V*I),se=l(G*I);if(te)return{x:Mt,y:yt};if(se!==yt)throw new Error("invZ was invalid");return{x:oe,y:me}}clearCofactor(){let{h:I}=e;return I===yt?this:this.multiplyUnsafe(I)}static fromHex(I,K=!1){let{d:V,a:G}=e,te=r.BYTES;I=ve("pointHex",I,te);let oe=I.slice(),me=I[te-1];oe[te-1]=me&-129;let se=tr(oe);se===Mt||(K?g(se,u):g(se,r.ORDER));let fe=l(se*se),Fe=l(fe-yt),De=l(V*fe-G),{isValid:je,value:Je}=f(Fe,De);if(!je)throw new Error("Point.fromHex: invalid y coordinate");let Ve=(Je&yt)===yt,st=(me&128)!==0;if(!K&&Je===Mt&&st)throw new Error("Point.fromHex: x=0 and x_0=1");return st!==Ve&&(Je=l(-Je)),_.fromAffine({x:Je,y:se})}static fromPrivateKey(I){return H(I).point}toRawBytes(){let{x:I,y:K}=this.toAffine(),V=Kr(K,r.BYTES);return V[V.length-1]|=I&yt?128:0,V}toHex(){return er(this.toRawBytes())}}_.BASE=new _(e.Gx,e.Gy,yt,l(e.Gx*e.Gy)),_.ZERO=new _(Mt,yt,yt,Mt);let{BASE:A,ZERO:P}=_,D=ms(_,a*8);function W(N){return de(N,n)}function Q(N){return W(tr(N))}function H(N){let I=a;N=ve("private key",N,I);let K=ve("hashed private key",o(N),2*I),V=h(K.slice(0,I)),G=K.slice(I,2*I),te=Q(V),oe=A.multiply(te),me=oe.toRawBytes();return{head:V,prefix:G,scalar:te,point:oe,pointBytes:me}}function ne(N){return H(N).pointBytes}function ge(N=new Uint8Array,...I){let K=Ot(...I);return Q(o(p(K,ve("context",N),!!i)))}function Ze(N,I,K={}){N=ve("message",N),i&&(N=i(N));let{prefix:V,scalar:G,pointBytes:te}=H(I),oe=ge(K.context,V,N),me=A.multiply(oe).toRawBytes(),se=ge(K.context,me,te,N),fe=W(oe+se*G);x(fe);let Fe=Ot(me,Kr(fe,r.BYTES));return ve("result",Fe,a*2)}let T=pw;function k(N,I,K,V=T){let{context:G,zip215:te}=V,oe=r.BYTES;N=ve("signature",N,2*oe),I=ve("message",I),i&&(I=i(I));let me=tr(N.slice(oe,2*oe)),se,fe,Fe;try{se=_.fromHex(K,te),fe=_.fromHex(N.slice(0,oe),te),Fe=A.multiplyUnsafe(me)}catch{return!1}if(!te&&se.isSmallOrder())return!1;let De=ge(G,fe.toRawBytes(),se.toRawBytes(),I);return fe.add(se.multiplyUnsafe(De)).subtract(Fe).clearCofactor().equals(_.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:ne,sign:Ze,verify:k,ExtendedPoint:_,utils:{getExtendedPublicKey:H,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,I=_.BASE){return I._setWindowSize(N),I.multiply(BigInt(3)),I}}}}var LI=BigInt(0),PI=BigInt(1);var Fc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ih=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GI=BigInt(0),gw=BigInt(1),Kc=BigInt(2),xw=BigInt(5),Rh=BigInt(10),bw=BigInt(20),ww=BigInt(40),Ch=BigInt(80);function Ew(t){let e=Fc,n=t*t%e*t%e,i=Ce(n,Kc,e)*n%e,o=Ce(i,gw,e)*t%e,s=Ce(o,xw,e)*o%e,a=Ce(s,Rh,e)*s%e,c=Ce(a,bw,e)*a%e,u=Ce(c,ww,e)*c%e,l=Ce(u,Ch,e)*u%e,f=Ce(l,Ch,e)*u%e,h=Ce(f,Rh,e)*s%e;return{pow_p_5_8:Ce(h,Kc,e)*t%e,b2:n}}function vw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function _w(t,e){let r=Fc,n=de(e*e*e,r),i=de(n*n*e,r),o=Ew(t*i).pow_p_5_8,s=de(t*n*o,r),a=de(e*s*s,r),c=s,u=de(s*Ih,r),l=a===t,f=a===de(-t,r),h=a===de(-t*Ih,r);return l&&(s=c),(f||h)&&(s=u),_h(s,r)&&(s=de(-s,r)),{isValid:l||f,value:s}}var xr=ps(Fc,void 0,!0),qc={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:xr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Pc,randomBytes:hn,adjustScalarBytes:vw,uvRatio:_w},ri=gs(qc);function Th(t,e,r){if(e.length>255)throw new Error("Context is too big");return as(Rc("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var YI=gs({...qc,domain:Th}),WI=gs({...qc,domain:Th,prehash:Pc});var Aw=(xr.ORDER+BigInt(3))/BigInt(8),QI=xr.pow(Kc,Aw),XI=xr.sqrt(xr.neg(xr.ONE)),ZI=(xr.ORDER-BigInt(5))/BigInt(8),jI=BigInt(486662);var JI=Ah(xr,xr.neg(BigInt(486664)));var eR=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tR=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),rR=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),nR=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var iR=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ni=32,br=64,xs=32;async function Bh(){let t=ri.utils.randomPrivateKey(),e=ri.getPublicKey(t);return{privateKey:Nh(t,e),publicKey:e}}async function Lh(t){if(t.length!==xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=ri.getPublicKey(e);return{privateKey:Nh(e,r),publicKey:r}}async function Ph(t,e){let r=t.subarray(0,xs);return ri.sign(e,r)}async function Dh(t,e,r){return ri.verify(e,r,t)}function Nh(t,e){let r=new Uint8Array(br);for(let n=0;n<xs;n++)r[n]=t[n],r[xs+n]=e[n];return r}function Me(t,e){e==null&&(e=t.reduce((i,o)=>i+o.length,0));let r=Dt(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return cn(r)}var dt={get(t=globalThis){let e=t.crypto;if(e==null||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-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Vc={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function bs(t){let e=t?.algorithm??"AES-GCM",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"SHA-256",o=t?.saltLength??16,s=t?.iterations??32767,a=dt.get();r*=8;async function c(f,h){let p=a.getRandomValues(new Uint8Array(o)),d=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:d};typeof h=="string"&&(h=Y(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},w=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,w,{name:e,length:r},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},w=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,w,{name:e,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,f);return Me([p,m.iv,new Uint8Array(g)])}async function u(f,h){let p=f.subarray(0,o),d=f.subarray(o,o+n),m=f.subarray(o+n),y={name:e,iv:d};typeof h=="string"&&(h=Y(h));let g;if(h.length===0)try{let w={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},C=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,C,{name:e,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},C=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,C,{name:e,length:r},!0,["decrypt"])}let x=await a.subtle.decrypt(y,g,m);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function ii(t,e){let n=await bs().encrypt(t,e);return un.encode(n)}var tu=J(Yc(),1),vd=J(pd(),1),_d=J(yn(),1),ru=J(eu(),1),Ad=J(Ed(),1);function Nw(){_d.default._configure(),tu.default._configure(vd.default),ru.default._configure(Ad.default)}Nw();var Sd=["uint64","int64","sint64","fixed64","sfixed64"];function kw(t){for(let e of Sd){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function nu(t){return kw(new tu.default(t))}function Ow(t){for(let e of Sd){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function iu(){return Ow(ru.default.create())}function tt(t,e){let r=nu(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function rt(t,e){let r=iu();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var si;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(si||(si={}));function As(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function ou(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return As("enum",si.VARINT,r,n)}function nt(t,e){return As("message",si.LENGTH_DELIMITED,t,e)}var Te;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(Te||(Te={}));var su;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})(su||(su={}));(function(t){t.codec=()=>ou(su)})(Te||(Te={}));var ir;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Te.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=Te.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(ir||(ir={}));var or;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Te.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=Te.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(or||(or={}));var Ji=class{_key;constructor(e){this._key=ai(e,ni)}async verify(e,r){return Dh(this._key,r,e)}marshal(){return this._key}get bytes(){return ir.encode({Type:Te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},xn=class{_key;_publicKey;constructor(e,r){this._key=ai(e,br),this._publicKey=ai(r,ni)}async sign(e){return Ph(this._key,e)}get public(){return new Ji(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:Te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=Nr.digest(this.public.bytes);return Oe.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Mw(t){if(t.length>br){t=ai(t,br+ni);let n=t.subarray(0,br),i=t.subarray(br,t.length);return new xn(n,i)}t=ai(t,br);let e=t.subarray(0,br),r=t.subarray(ni);return new xn(e,r)}function Uw(t){return t=ai(t,ni),new Ji(t)}async function Kw(){let{privateKey:t,publicKey:e}=await Bh();return new xn(t,e)}async function Id(t){let{privateKey:e,publicKey:r}=await Lh(t);return new xn(e,r)}function ai(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}function ee(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var JR=J(ke(),1),e4=J(Jo(),1),Rd=J(ye(),1);function Ft(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Me([new Uint8Array(e-r.length),r])}return ee(r,"base64url")}function gt(t){let e=Cd(t);return new Rd.default.jsbn.BigInteger(ee(e,"base16"),16)}function Cd(t,e){let r=Y(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Me([new Uint8Array(e-r.length),r])}return r}var Fw={"P-256":256,"P-384":384,"P-521":521},qw=Object.keys(Fw),f4=qw.join(" / ");async function Td(t,e){let r=un.decode(t);return bs().decrypt(r,e)}var hu={};He(hu,{MAX_KEY_SIZE:()=>no,RsaPrivateKey:()=>ci,RsaPublicKey:()=>ro,fromJwk:()=>Zw,generateKeyPair:()=>jw,unmarshalRsaPrivateKey:()=>Qw,unmarshalRsaPublicKey:()=>Xw});var to=J(ye(),1);var Q4=J(kd(),1);function wn(t){if(isNaN(t)||t<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return hn(t)}var L4=J(rs(),1),lu=J(ye(),1);function Od(t,e){return e.map(r=>gt(t[r]))}function Md(t){return lu.default.pki.setRsaPrivateKey(...Od(t,["n","e","d","p","q","dp","dq","qi"]))}function Ud(t){return lu.default.pki.setRsaPublicKey(...Od(t,["n","e"]))}var En={};He(En,{jwkToPkcs1:()=>zw,jwkToPkix:()=>Gw,pkcs1ToJwk:()=>$w,pkixToJwk:()=>Hw});var N4=J(qi(),1),k4=J(rs(),1);var wr=J(ye(),1);function $w(t){let e=wr.default.asn1.fromDer(ee(t,"ascii")),r=wr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Ft(r.n),e:Ft(r.e),d:Ft(r.d),p:Ft(r.p),q:Ft(r.q),dp:Ft(r.dP),dq:Ft(r.dQ),qi:Ft(r.qInv),alg:"RS256"}}function zw(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=wr.default.pki.privateKeyToAsn1({n:gt(t.n),e:gt(t.e),d:gt(t.d),p:gt(t.p),q:gt(t.q),dP:gt(t.dp),dQ:gt(t.dq),qInv:gt(t.qi)});return Y(wr.default.asn1.toDer(e).getBytes(),"ascii")}function Hw(t){let e=wr.default.asn1.fromDer(ee(t,"ascii")),r=wr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Ft(r.n),e:Ft(r.e)}}function Gw(t){if(t.n==null||t.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=wr.default.pki.publicKeyToAsn1({n:gt(t.n),e:gt(t.e)});return Y(wr.default.asn1.toDer(e).getBytes(),"ascii")}async function Kd(t){let e=await dt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Vd(e);return{privateKey:r[0],publicKey:r[1]}}async function fu(t){let r=[await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Yw(t)],n=await Vd({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function Fd(t,e){let r=await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await dt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function qd(t,e,r){let n=await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return dt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)}async function Vd(t){if(t.privateKey==null||t.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([dt.get().subtle.exportKey("jwk",t.privateKey),dt.get().subtle.exportKey("jwk",t.publicKey)])}async function Yw(t){return dt.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function $d(t,e,r,n){let i=e?Ud(t):Md(t),o=ee(Uint8Array.from(r),"ascii"),s=n(o,i);return Y(s,"ascii")}function zd(t,e){return $d(t,!0,e,(r,n)=>n.encrypt(r))}function Hd(t,e){return $d(t,!1,e,(r,n)=>n.decrypt(r))}function Is(t){if(t.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(t.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Y(t.n,"base64url").length*8}var no=8192,ro=class{_key;constructor(e){this._key=e}async verify(e,r){return qd(this._key,r,e)}marshal(){return En.jwkToPkix(this._key)}get bytes(){return ir.encode({Type:Te.RSA,Data:this.marshal()}).subarray()}encrypt(e){return zd(this._key,e)}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},ci=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return wn(16)}async sign(e){return Fd(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new ro(this._publicKey)}decrypt(e){return Hd(this._key,e)}marshal(){return En.jwkToPkcs1(this._key)}get bytes(){return or.encode({Type:Te.RSA,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return ee(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new to.default.util.ByteBuffer(this.marshal()),i=to.default.asn1.fromDer(n),o=to.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return to.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function Qw(t){let e=En.pkcs1ToJwk(t);if(Is(e)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await fu(e);return new ci(r.privateKey,r.publicKey)}function Xw(t){let e=En.pkixToJwk(t);if(Is(e)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new ro(e)}async function Zw(t){if(Is(t)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await fu(t);return new ci(e.privateKey,e.publicKey)}async function jw(t){if(t>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Kd(t);return new ci(e.privateKey,e.publicKey)}var xu={};He(xu,{Secp256k1PrivateKey:()=>oo,Secp256k1PublicKey:()=>io,generateKeyPair:()=>dE,unmarshalSecp256k1PrivateKey:()=>fE,unmarshalSecp256k1PublicKey:()=>hE});var Jw=(t,e,r)=>t&e^~t&r,eE=(t,e,r)=>t&e^t&r^e&r,tE=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]),Vr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$r=new Uint32Array(64),Rs=class extends ei{constructor(){super(64,32,8,!1),this.A=Vr[0]|0,this.B=Vr[1]|0,this.C=Vr[2]|0,this.D=Vr[3]|0,this.E=Vr[4]|0,this.F=Vr[5]|0,this.G=Vr[6]|0,this.H=Vr[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,r,n,i,o,s,a,c]}set(e,r,n,i,o,s,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)$r[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=$r[f-15],p=$r[f-2],d=Nt(h,7)^Nt(h,18)^h>>>3,m=Nt(p,17)^Nt(p,19)^p>>>10;$r[f]=m+$r[f-7]+d+$r[f-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let h=Nt(a,6)^Nt(a,11)^Nt(a,25),p=l+h+Jw(a,c,u)+tE[f]+$r[f]|0,m=(Nt(n,2)^Nt(n,13)^Nt(n,22))+eE(n,i,o)|0;l=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+m|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,o,s,a,c,u,l)}roundClean(){$r.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},du=class extends Rs{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}},Gd=Or(()=>new Rs),e8=Or(()=>new du);function rE(t){let e=Xi(t);It(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:nE,hexToBytes:iE}=fs,vn={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=vn;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:nE(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=vn,r=typeof t=="string"?iE(t):t;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=vn._parseInt(r.subarray(2)),{d:s,l:a}=vn._parseInt(o);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,a=r(o),c=r(s);return`30${r(s+o+4)}02${c}${i}02${a}${n}`}},Er=BigInt(0),Ct=BigInt(1),o8=BigInt(2),Yd=BigInt(3),s8=BigInt(4);function oE(t){let e=rE(t),{Fp:r}=e,n=e.toBytes||((d,m,y)=>{let g=m.toAffine();return Ot(Uint8Array.from([4]),r.toBytes(g.x),r.toBytes(g.y))}),i=e.fromBytes||(d=>{let m=d.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),g=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:g}});function o(d){let{a:m,b:y}=e,g=r.sqr(d),x=r.mul(g,d);return r.add(r.add(x,r.mul(d,m)),y)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(d){return typeof d=="bigint"&&Er<d&&d<e.n}function a(d){if(!s(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:g,n:x}=e;if(m&&typeof d!="bigint"){if(d instanceof Uint8Array&&(d=er(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(y*2,"0")}let w;try{w=typeof d=="bigint"?d:kt(ve("private key",d,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof d}`)}return g&&(w=de(w,x)),a(w),w}let u=new Map;function l(d){if(!(d instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(m,y,g){if(this.px=m,this.py=y,this.pz=g,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(g==null||!r.isValid(g))throw new Error("z required")}static fromAffine(m){let{x:y,y:g}=m||{};if(!m||!r.isValid(y)||!r.isValid(g))throw new Error("invalid affine point");if(m instanceof f)throw new Error("projective point not allowed");let x=w=>r.eql(w,r.ZERO);return x(y)&&x(g)?f.ZERO:new f(y,g,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(g=>g.pz));return m.map((g,x)=>g.toAffine(y[x])).map(f.fromAffine)}static fromHex(m){let y=f.fromAffine(i(ve("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint)return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let g=r.sqr(y),x=o(m);if(!r.eql(g,x))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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){l(m);let{px:y,py:g,pz:x}=this,{px:w,py:C,pz:_}=m,A=r.eql(r.mul(y,_),r.mul(w,x)),P=r.eql(r.mul(g,_),r.mul(C,x));return A&&P}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,g=r.mul(y,Yd),{px:x,py:w,pz:C}=this,_=r.ZERO,A=r.ZERO,P=r.ZERO,D=r.mul(x,x),W=r.mul(w,w),Q=r.mul(C,C),H=r.mul(x,w);return H=r.add(H,H),P=r.mul(x,C),P=r.add(P,P),_=r.mul(m,P),A=r.mul(g,Q),A=r.add(_,A),_=r.sub(W,A),A=r.add(W,A),A=r.mul(_,A),_=r.mul(H,_),P=r.mul(g,P),Q=r.mul(m,Q),H=r.sub(D,Q),H=r.mul(m,H),H=r.add(H,P),P=r.add(D,D),D=r.add(P,D),D=r.add(D,Q),D=r.mul(D,H),A=r.add(A,D),Q=r.mul(w,C),Q=r.add(Q,Q),D=r.mul(Q,H),_=r.sub(_,D),P=r.mul(Q,W),P=r.add(P,P),P=r.add(P,P),new f(_,A,P)}add(m){l(m);let{px:y,py:g,pz:x}=this,{px:w,py:C,pz:_}=m,A=r.ZERO,P=r.ZERO,D=r.ZERO,W=e.a,Q=r.mul(e.b,Yd),H=r.mul(y,w),ne=r.mul(g,C),ge=r.mul(x,_),Ze=r.add(y,g),T=r.add(w,C);Ze=r.mul(Ze,T),T=r.add(H,ne),Ze=r.sub(Ze,T),T=r.add(y,x);let k=r.add(w,_);return T=r.mul(T,k),k=r.add(H,ge),T=r.sub(T,k),k=r.add(g,x),A=r.add(C,_),k=r.mul(k,A),A=r.add(ne,ge),k=r.sub(k,A),D=r.mul(W,T),A=r.mul(Q,ge),D=r.add(A,D),A=r.sub(ne,D),D=r.add(ne,D),P=r.mul(A,D),ne=r.add(H,H),ne=r.add(ne,H),ge=r.mul(W,ge),T=r.mul(Q,T),ne=r.add(ne,ge),ge=r.sub(H,ge),ge=r.mul(W,ge),T=r.add(T,ge),H=r.mul(ne,T),P=r.add(P,H),H=r.mul(k,T),A=r.mul(Ze,A),A=r.sub(A,H),H=r.mul(Ze,ne),D=r.mul(k,D),D=r.add(D,H),new f(A,P,D)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return p.wNAFCached(this,u,m,y=>{let g=r.invertBatch(y.map(x=>x.pz));return y.map((x,w)=>x.toAffine(g[w])).map(f.fromAffine)})}multiplyUnsafe(m){let y=f.ZERO;if(m===Er)return y;if(a(m),m===Ct)return this;let{endo:g}=e;if(!g)return p.unsafeLadder(this,m);let{k1neg:x,k1:w,k2neg:C,k2:_}=g.splitScalar(m),A=y,P=y,D=this;for(;w>Er||_>Er;)w&Ct&&(A=A.add(D)),_&Ct&&(P=P.add(D)),D=D.double(),w>>=Ct,_>>=Ct;return x&&(A=A.negate()),C&&(P=P.negate()),P=new f(r.mul(P.px,g.beta),P.py,P.pz),A.add(P)}multiply(m){a(m);let y=m,g,x,{endo:w}=e;if(w){let{k1neg:C,k1:_,k2neg:A,k2:P}=w.splitScalar(y),{p:D,f:W}=this.wNAF(_),{p:Q,f:H}=this.wNAF(P);D=p.constTimeNegate(C,D),Q=p.constTimeNegate(A,Q),Q=new f(r.mul(Q.px,w.beta),Q.py,Q.pz),g=D.add(Q),x=W.add(H)}else{let{p:C,f:_}=this.wNAF(y);g=C,x=_}return f.normalizeZ([g,x])[0]}multiplyAndAddUnsafe(m,y,g){let x=f.BASE,w=(_,A)=>A===Er||A===Ct||!_.equals(x)?_.multiplyUnsafe(A):_.multiply(A),C=w(this,y).add(w(m,g));return C.is0()?void 0:C}toAffine(m){let{px:y,py:g,pz:x}=this,w=this.is0();m==null&&(m=w?r.ONE:r.inv(x));let C=r.mul(y,m),_=r.mul(g,m),A=r.mul(x,m);if(w)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:C,y:_}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Ct)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Ct?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(f,this,m)}toHex(m=!0){return er(this.toRawBytes(m))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=ms(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function sE(t){let e=Xi(t);return It(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Wd(t){let e=sE(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(T){return Er<T&&T<r.ORDER}function a(T){return de(T,n)}function c(T){return hs(T,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:f,isWithinCurveOrder:h}=oE({...e,toBytes(T,k,L){let N=k.toAffine(),I=r.toBytes(N.x),K=Ot;return L?K(Uint8Array.from([k.hasEvenY()?2:3]),I):K(Uint8Array.from([4]),I,r.toBytes(N.y))},fromBytes(T){let k=T.length,L=T[0],N=T.subarray(1);if(k===i&&(L===2||L===3)){let I=kt(N);if(!s(I))throw new Error("Point is not on curve");let K=f(I),V=r.sqrt(K),G=(V&Ct)===Ct;return(L&1)===1!==G&&(V=r.neg(V)),{x:I,y:V}}else if(k===o&&L===4){let I=r.fromBytes(N.subarray(0,r.BYTES)),K=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:I,y:K}}else throw new Error(`Point of length ${k} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=T=>er(gr(T,e.nByteLength));function d(T){let k=n>>Ct;return T>k}function m(T){return d(T)?a(-T):T}let y=(T,k,L)=>kt(T.slice(k,L));class g{constructor(k,L,N){this.r=k,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(k){let L=e.nByteLength;return k=ve("compactSignature",k,L*2),new g(y(k,0,L),y(k,L,2*L))}static fromDER(k){let{r:L,s:N}=vn.toSig(ve("DER",k));return new g(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(k){return new g(this.r,this.s,k)}recoverPublicKey(k){let{r:L,s:N,recovery:I}=this,K=P(ve("msgHash",k));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let V=I===2||I===3?L+e.n:L;if(V>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let G=I&1?"03":"02",te=u.fromHex(G+p(V)),oe=c(V),me=a(-K*oe),se=a(N*oe),fe=u.BASE.multiplyAndAddUnsafe(te,me,se);if(!fe)throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return dn(this.toDERHex())}toDERHex(){return vn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dn(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let x={isValidPrivateKey(T){try{return l(T),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let T=e.randomBytes(r.BYTES+8),k=Sh(T,n);return gr(k,e.nByteLength)},precompute(T=8,k=u.BASE){return k._setWindowSize(T),k.multiply(BigInt(3)),k}};function w(T,k=!0){return u.fromPrivateKey(T).toRawBytes(k)}function C(T){let k=T instanceof Uint8Array,L=typeof T=="string",N=(k||L)&&T.length;return k?N===i||N===o:L?N===2*i||N===2*o:T instanceof u}function _(T,k,L=!0){if(C(T))throw new Error("first arg must be private key");if(!C(k))throw new Error("second arg must be public key");return u.fromHex(k).multiply(l(T)).toRawBytes(L)}let A=e.bits2int||function(T){let k=kt(T),L=T.length*8-e.nBitLength;return L>0?k>>BigInt(L):k},P=e.bits2int_modN||function(T){return a(A(T))},D=Qi(e.nBitLength);function W(T){if(typeof T!="bigint")throw new Error("bigint expected");if(!(Er<=T&&T<D))throw new Error(`bigint expected < 2^${e.nBitLength}`);return gr(T,e.nByteLength)}function Q(T,k,L=H){if(["recovered","canonical"].some(De=>De in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:I}=e,{lowS:K,prehash:V,extraEntropy:G}=L;K==null&&(K=!0),T=ve("msgHash",T),V&&(T=ve("prehashed msgHash",N(T)));let te=P(T),oe=l(k),me=[W(oe),W(te)];if(G!=null){let De=G===!0?I(r.BYTES):G;me.push(ve("extraEntropy",De,r.BYTES))}let se=Ot(...me),fe=te;function Fe(De){let je=A(De);if(!h(je))return;let Je=c(je),Ve=u.BASE.multiply(je).toAffine(),st=a(Ve.x);if(st===Er)return;let lr=a(Je*a(fe+st*oe));if(lr===Er)return;let tn=(Ve.x===st?0:2)|Number(Ve.y&Ct),Mi=lr;return K&&d(lr)&&(Mi=m(lr),tn^=1),new g(st,Mi,tn)}return{seed:se,k2sig:Fe}}let H={lowS:e.lowS,prehash:!1},ne={lowS:e.lowS,prehash:!1};function ge(T,k,L=H){let{seed:N,k2sig:I}=Q(T,k,L),K=e;return kc(K.hash.outputLen,K.nByteLength,K.hmac)(N,I)}u.BASE._setWindowSize(8);function Ze(T,k,L,N=ne){let I=T;if(k=ve("msgHash",k),L=ve("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:K,prehash:V}=N,G,te;try{if(typeof I=="string"||I instanceof Uint8Array)try{G=g.fromDER(I)}catch(Ve){if(!(Ve instanceof vn.Err))throw Ve;G=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:Ve,s:st}=I;G=new g(Ve,st)}else throw new Error("PARSE");te=u.fromHex(L)}catch(Ve){if(Ve.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(K&&G.hasHighS())return!1;V&&(k=e.hash(k));let{r:oe,s:me}=G,se=P(k),fe=c(me),Fe=a(se*fe),De=a(oe*fe),je=u.BASE.multiplyAndAddUnsafe(te,Fe,De)?.toAffine();return je?a(je.x)===oe:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:_,sign:ge,verify:Ze,ProjectivePoint:u,Signature:g,utils:x}}var Cs=class extends Jn{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,yr.hash(e);let n=Wi(r);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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(e){return yr.exists(this),this.iHash.update(e),this}digestInto(e){yr.exists(this),yr.bytes(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},pu=(t,e,r)=>new Cs(t,e).update(r).digest();pu.create=(t,e)=>new Cs(t,e);function aE(t){return{hash:t,hmac:(e,...r)=>pu(t,e,as(...r)),randomBytes:hn}}function Qd(t,e){let r=n=>Wd({...t,...aE(n)});return Object.freeze({...r(e),create:r})}var jd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cE=BigInt(1),mu=BigInt(2),Zd=(t,e)=>(t+e/mu)/e;function uE(t){let e=jd,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Ce(l,r,e)*l%e,h=Ce(f,r,e)*l%e,p=Ce(h,mu,e)*u%e,d=Ce(p,i,e)*p%e,m=Ce(d,o,e)*d%e,y=Ce(m,a,e)*m%e,g=Ce(y,c,e)*y%e,x=Ce(g,a,e)*m%e,w=Ce(x,r,e)*l%e,C=Ce(w,s,e)*d%e,_=Ce(C,n,e)*u%e,A=Ce(_,mu,e);if(!yu.eql(yu.sqr(A),t))throw new Error("Cannot find square root");return A}var yu=ps(jd,void 0,void 0,{sqrt:uE}),vr=Qd({a:BigInt(0),b:BigInt(7),Fp:yu,n:Xd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=Xd,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=Zd(o*t,e),c=Zd(-n*t,e),u=de(t-a*r-c*i,e),l=de(-a*n-c*o,e),f=u>s,h=l>s;if(f&&(u=e-u),h&&(l=e-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}}},Gd),A8=BigInt(0);var S8=vr.ProjectivePoint;function Jd(){return vr.utils.randomPrivateKey()}async function ep(t,e){let{digest:r}=await et.digest(e);try{return vr.sign(r,t).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}async function tp(t,e,r){try{let{digest:n}=await et.digest(r);return vr.verify(e,n,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function rp(t){return vr.ProjectivePoint.fromHex(t).toRawBytes(!0)}function np(t){try{vr.getPublicKey(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function gu(t){try{vr.ProjectivePoint.fromHex(t)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function ip(t){try{return vr.getPublicKey(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var io=class{_key;constructor(e){gu(e),this._key=e}async verify(e,r){return tp(this._key,r,e)}marshal(){return rp(this._key)}get bytes(){return ir.encode({Type:Te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},oo=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??ip(e),np(this._key),gu(this._publicKey)}async sign(e){return ep(this._key,e)}get public(){return new io(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:Te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return ee(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function fE(t){return new oo(t)}function hE(t){return new io(t)}async function dE(){let t=Jd();return new oo(t)}var _r={rsa:hu,ed25519:au,secp256k1:xu};function bu(t){let e=Object.keys(_r).join(" / ");return new E(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function wu(t){if(t=t.toLowerCase(),t==="rsa"||t==="ed25519"||t==="secp256k1")return _r[t];throw bu(t)}async function Bs(t,e){return wu(t).generateKeyPair(e??2048)}function so(t){let e=ir.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Te.RSA:return _r.rsa.unmarshalRsaPublicKey(r);case Te.Ed25519:return _r.ed25519.unmarshalEd25519PublicKey(r);case Te.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw bu(e.Type??"RSA")}}function op(t,e){return e=(e??"rsa").toLowerCase(),wu(e),t.bytes}async function ui(t){let e=or.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Te.RSA:return _r.rsa.unmarshalRsaPrivateKey(r);case Te.Ed25519:return _r.ed25519.unmarshalEd25519PrivateKey(r);case Te.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw bu(e.Type??"RSA")}}function sp(t,e){return e=(e??"rsa").toLowerCase(),wu(e),t.bytes}async function ao(t,e){try{let i=await Td(t,e);return await ui(i)}catch{}let r=Ts.default.pki.decryptRsaPrivateKey(t,e);if(r===null)throw new E("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Ts.default.asn1.toDer(Ts.default.pki.privateKeyToAsn1(r));return n=Y(n.getBytes(),"ascii"),_r.rsa.unmarshalRsaPrivateKey(n)}var Eu=Symbol.for("@libp2p/content-routing");var co=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new _u(e,r))}},vu=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},_u=globalThis.CustomEvent??vu;var Au=Symbol.for("@libp2p/peer-discovery");var Su=Symbol.for("@libp2p/peer-routing");var X8=J(Ho(),1),mE=J(ye(),1);var cp=J(Qa(),1),up=J(ke(),1),ap={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function uo(t,e,r,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(ap).join(" / ");throw new E(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let o=ap[i],s=(0,cp.default)(t,e,r,n,o);return up.default.encode64(s,null)}var bt=J(Ru(),1);bt.default.formatters.b=t=>t==null?"undefined":Oe.baseEncode(t);bt.default.formatters.t=t=>t==null?"undefined":mt.baseEncode(t);bt.default.formatters.m=t=>t==null?"undefined":un.baseEncode(t);bt.default.formatters.p=t=>t==null?"undefined":t.toString();bt.default.formatters.c=t=>t==null?"undefined":t.toString();bt.default.formatters.k=t=>t==null?"undefined":t.toString();bt.default.formatters.a=t=>t==null?"undefined":t.toString();function BE(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function ie(t){let e=BE(`${t}:trace`);return bt.default.enabled(`${t}:trace`)&&bt.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,bt.default)(`${t}:trace`)),Object.assign((0,bt.default)(t),{error:(0,bt.default)(`${t}:error`),trace:e})}var Cu=Symbol.for("@libp2p/peer-id");function Ds(t){return t!=null&&!!t[Cu]}var LE=Symbol.for("nodejs.util.inspect.custom"),dp=Object.values(kr).map(t=>t.decoder).reduce((t,e)=>t.or(e),kr.identity.decoder),pp=114,Tu=36,Bu=37,lo=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Cu]=!0;toString(){return this.string==null&&(this.string=Oe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Pt.createV1(pp,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return Le(this.multihash.bytes,e);if(typeof e=="string")return pe(e).equals(this);if(e?.multihash?.bytes!=null)return Le(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[LE](){return`PeerId(${this.toString()})`}},An=class extends lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sn=class extends lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},In=class extends lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function mp(t){if(t.type==="RSA")return new An(t);if(t.type==="Ed25519")return new Sn(t);if(t.type==="secp256k1")return new In(t);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function pe(t,e){if(e=e??dp,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=ln(Oe.decode(`z${t}`));return t.startsWith("12D")?new Sn({multihash:r}):t.startsWith("16U")?new In({multihash:r}):new An({multihash:r})}return di(dp.decode(t))}function di(t){try{let e=ln(t);if(e.code===Nr.code){if(e.digest.length===Tu)return new Sn({multihash:e});if(e.digest.length===Bu)return new In({multihash:e})}if(e.code===et.code)return new An({multihash:e})}catch{return PE(Pt.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function PE(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==pp)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===et.code)return new An({multihash:t.multihash});if(e.code===Nr.code){if(e.digest.length===Tu)return new Sn({multihash:t.multihash});if(e.digest.length===Bu)return new In({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function pi(t,e){return t.length===Tu?new Sn({multihash:Jt(Nr.code,t),privateKey:e}):t.length===Bu?new In({multihash:Jt(Nr.code,t),privateKey:e}):new An({multihash:await et.digest(t),publicKey:t,privateKey:e})}var Ns=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var Ar="/",yp=new TextEncoder().encode(Ar),ks=yp[0],sr=class t{_buf;constructor(e,r){if(typeof e=="string")this._buf=Y(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ks)throw new Error("Invalid key")}toString(e="utf8"){return ee(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new t(e.join(Ar))}static random(){return new t(Ns().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new t(e):typeof e.uint8Array=="function"?new t(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=yp),this._buf[0]!==ks){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ks,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ks;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let o=r[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return r.length<n.length}reverse(){return t.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ar).slice(1)}type(){return DE(this.baseNamespace())}name(){return NE(this.baseNamespace())}instance(e){return new t(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ar)||(e+=Ar),e+=this.type(),new t(e)}parent(){let e=this.list();return e.length===1?new t(Ar):new t(e.slice(0,-1).join(Ar))}child(e){return this.toString()===Ar?e:e.toString()===Ar?this:new t(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 t.withNamespaces([...this.namespaces(),...kE(e.map(r=>r.namespaces()))])}};function DE(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function NE(t){let e=t.split(":");return e[e.length-1]}function kE(t){return[].concat(...t)}var Sp=J(Ap(),1),zr=Sp.default;var kp=J(Np(),1);var ce;(function(t){t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(ce||(ce={}));var Us=ie("libp2p:keychain"),JE="/pkcs8/",Op="/info/",Rn=new WeakMap,Cn={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},Pu={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Sr(t){return t==null||typeof t!="string"?!1:t===(0,kp.default)(t.trim())&&t.length>0}async function be(){let r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function ar(t){return new sr(JE+t)}function Hr(t){return new sr(Op+t)}var Tn=class{components;init;constructor(e,r){if(this.components=e,this.init=zr(Pu,r),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<Cn.minKeyLength)throw new Error(`dek.keyLength must be least ${Cn.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<Cn.minSaltLength)throw new Error(`dek.saltLength must be least ${Cn.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<Cn.minIterationCount)throw new Error(`dek.iterationCount must be least ${Cn.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?uo(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Rn.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},Pu),r=Math.ceil(Cn.minSaltLength/3)*3;return e.dek.salt=ee(wn(r),"base64"),e}static get options(){return Pu}async createKey(e,r,n=2048){if(!Sr(e)||e==="self")throw await be(),new E("Invalid key name",ce.ERR_INVALID_KEY_NAME);if(typeof r!="string")throw await be(),new E("Invalid key type",ce.ERR_INVALID_KEY_TYPE);let i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E("Key name already exists",ce.ERR_KEY_ALREADY_EXISTS);switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await be(),new E("Invalid RSA key size",ce.ERR_INVALID_KEY_SIZE);break;default:break}let s;try{let a=await Bs(r,n),c=await a.id(),u=Rn.get(this);if(u==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let l=u.dek,f=await a.export(l);s={name:e,id:c};let h=this.components.datastore.batch();h.put(i,Y(f)),h.put(Hr(e),Y(JSON.stringify(s))),await h.commit()}catch(a){throw await be(),a}return s}async listKeys(){let e={prefix:Op},r=[];for await(let n of this.components.datastore.query(e))r.push(JSON.parse(ee(n.value)));return r}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new E(`Key with id '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND);return n}catch(r){throw await be(),r}}async findKeyByName(e){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);let r=Hr(e);try{let n=await this.components.datastore.get(r);return JSON.parse(ee(n))}catch(n){throw await be(),Us.error(n),new E(`Key '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);let r=ar(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(r),i.delete(Hr(e)),await i.commit(),n}async renameKey(e,r){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid old key name '${e}'`,ce.ERR_OLD_KEY_NAME_INVALID);if(!Sr(r)||r==="self")throw await be(),new E(`Invalid new key name '${r}'`,ce.ERR_NEW_KEY_NAME_INVALID);let n=ar(e),i=ar(r),o=Hr(e),s=Hr(r);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${r}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(o),l=JSON.parse(ee(u));l.name=r;let f=this.components.datastore.batch();return f.put(i,c),f.put(s,Y(JSON.stringify(l))),f.delete(n),f.delete(o),await f.commit(),l}catch(c){throw await be(),c}}async exportKey(e,r){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),new E("Password is required",ce.ERR_PASSWORD_REQUIRED);let n=ar(e);try{let i=await this.components.datastore.get(n),o=ee(i),s=Rn.get(this);if(s==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let a=s.dek;return await(await ao(o,a)).export(r)}catch(i){throw await be(),i}}async exportPeerId(e){let r="temporary-password",n=await this.exportKey(e,r),i=await ao(n,r);return pi(i.public.bytes,i.bytes)}async importKey(e,r,n){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),new E("PEM encoded key is required",ce.ERR_PEM_REQUIRED);let i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${e}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);let s;try{s=await ao(r,n)}catch{throw await be(),new E("Cannot read the key, most likely the password is wrong",ce.ERR_CANNOT_READ_KEY)}let a;try{a=await s.id();let l=Rn.get(this);if(l==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let f=l.dek;r=await s.export(f)}catch(l){throw await be(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,Y(r)),u.put(Hr(e),Y(JSON.stringify(c))),await u.commit(),c}async importPeer(e,r){try{if(!Sr(e))throw new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw new E("PeerId is required",ce.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new E("PeerId.privKey is required",ce.ERR_MISSING_PRIVATE_KEY);let n=await ui(r.privateKey),i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${e}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);let s=Rn.get(this);if(s==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let a=s.dek,c=await n.export(a),u={name:e,id:r.toString()},l=this.components.datastore.batch();return l.put(i,Y(c)),l.put(Hr(e),Y(JSON.stringify(u))),await l.commit(),u}catch(n){throw await be(),n}}async getPrivateKey(e){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);try{let r=ar(e),n=await this.components.datastore.get(r);return ee(n)}catch(r){throw await be(),Us.error(r),new E(`Key '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,r){if(typeof e!="string")throw await be(),new E(`Invalid old pass type '${typeof e}'`,ce.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await be(),new E(`Invalid new pass type '${typeof r}'`,ce.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await be(),new E(`Invalid pass length ${r.length}`,ce.ERR_INVALID_PASS_LENGTH);Us("recreating keychain");let n=Rn.get(this);if(n==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=r;let o=r!=null&&this.init.dek?.salt!=null?uo(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Rn.set(this,{dek:o});let s=await this.listKeys();for(let a of s){let c=await this.components.datastore.get(ar(a.name)),u=ee(c),l=await ao(u,i),f=o.toString(),h=await l.export(f),p=this.components.datastore.batch(),d={name:a.name,id:a.id};p.put(ar(a.name),Y(h)),p.put(Hr(a.name),Y(JSON.stringify(d))),await p.commit()}Us("keychain reconstructed")}};function Ir(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return r}var qt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return Ir(this.map.entries(),e=>[pe(e[0]),e[1]])}forEach(e){this.map.forEach((r,n)=>{e(r,pe(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),r)}keys(){return Ir(this.map.keys(),e=>pe(e))}values(){return this.map.values()}get size(){return this.map.size}};var Bn=class t{set;constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.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 Ir(this.set.entries(),e=>{let r=pe(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=pe(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ir(this.set.values(),e=>pe(e))}intersection(e){let r=new t;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new t;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new t;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var Du=class t{list;constructor(e){if(this.list=[],e!=null)for(let r of e)this.list.push(r.toString())}[Symbol.iterator](){return Ir(this.list.entries(),e=>pe(e[1]))}concat(e){let r=new t(this);for(let n of e)r.push(n);return r}entries(){return Ir(this.list.entries(),e=>[e[0],pe(e[1])])}every(e){return this.list.every((r,n)=>e(pe(r),n,this))}filter(e){let r=new t;return this.list.forEach((n,i)=>{let o=pe(n);e(o,i,this)&&r.push(o)}),r}find(e){let r=this.list.find((n,i)=>e(pe(n),i,this));if(r!=null)return pe(r)}findIndex(e){return this.list.findIndex((r,n)=>e(pe(r),n,this))}forEach(e){this.list.forEach((r,n)=>{e(pe(r),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return pe(e)}push(...e){for(let r of e)this.list.push(r.toString())}shift(){let e=this.list.shift();if(e!=null)return pe(e)}unshift(...e){let r=this.list.length;for(let n=e.length-1;n>-1;n--)r=this.list.unshift(e[n].toString());return r}get length(){return this.list.length}};var Nu;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.id!=null&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(Nu||(Nu={}));var Mp=async()=>{let t=await Bs("Ed25519"),e=await ev(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function ev(t){return pi(op(t.public),sp(t))}function Ks(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var Up=4294967296,fo=class t{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new t(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new t(r,n)}toBytes(e,r=0){let n=Ks(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new t;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>Up&&(i=0,++n>Up&&(n=0))),new t(n,i)}static fromNumber(e){if(e===0)return new t;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(i,n)}static fromBytes(e,r=0){let n=Ks(e),i=new t,o=0;if(e.length-r>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(r)&127)<<o*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;o=0}else for(;o<4;++o){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<o*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(r)&127)<<o*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;o<5;++o){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<o*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var tv=Math.pow(2,7),rv=Math.pow(2,14),nv=Math.pow(2,21),iv=Math.pow(2,28),ov=Math.pow(2,35),sv=Math.pow(2,42),av=Math.pow(2,49),cv=Math.pow(2,56),uv=Math.pow(2,63),Vt={encodingLength(t){return t<tv?1:t<rv?2:t<nv?3:t<iv?4:t<ov?5:t<sv?6:t<av?7:t<cv?8:t<uv?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Dt(Vt.encodingLength(t))),fo.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return fo.fromBytes(t,e).toNumber(!0)}};var Fp=Symbol.for("@achingbrain/uint8arraylist");function Kp(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function Fs(t){return!!t?.[Fp]}var Xe=class t{constructor(...e){Object.defineProperty(this,Fp,{value:!0}),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 r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Fs(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Fs(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=Kp(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Kp(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(Fs(e))for(let n=0;n<e.length;n++)this.set(r+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,r){let{bufs:n,length:i}=this._subList(e,r);return Me(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Me(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),o=new t;return o.length=i,o.bufs=n,o}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(r===c){n.push(s);break}n.push(s.subarray(0,r-a));break}n.push(s)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!Fs(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(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let p=this.get(f+h);if(n[h]!==p){l=Math.max(1,h-a[p]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=Dt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=mr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=Dt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=mr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Le(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};var qp={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var ho;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.publicKey!=null&&r.publicKey.byteLength>0&&(n.uint32(10),n.bytes(r.publicKey)),r.payloadType!=null&&r.payloadType.byteLength>0&&(n.uint32(18),n.bytes(r.payloadType)),r.payload!=null&&r.payload.byteLength>0&&(n.uint32(26),n.bytes(r.payload)),r.signature!=null&&r.signature.byteLength>0&&(n.uint32(42),n.bytes(r.signature)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(ho||(ho={}));var gi=class t{static createFromProtobuf=async e=>{let r=ho.decode(e),n=await pi(r.publicKey);return new t({peerId:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(e,r)=>{if(r.privateKey==null)throw new Error("Missing private key");let n=e.domain,i=e.codec,o=e.marshal(),s=Vp(n,i,o),c=await(await ui(r.privateKey)).sign(s.subarray());return new t({peerId:r,payloadType:i,payload:o,signature:c})};static openAndCertify=async(e,r)=>{let n=await t.createFromProtobuf(e);if(!await n.validate(r))throw new E("envelope signature is not valid for the given domain",qp.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:r,payloadType:n,payload:i,signature:o}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=ho.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Le(this.marshal(),e.marshal())}async validate(e){let r=Vp(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return so(this.peerId.publicKey).verify(r.subarray(),this.signature)}},Vp=(t,e,r)=>{let n=Y(t),i=Vt.encode(n.byteLength),o=Vt.encode(e.length),s=Vt.encode(r.length);return new Xe(i,n,o,e,s,r)};function $p(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var Ei=J(Mu(),1);var qs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,r!==void 0&&s>r))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return r[i]=s[0],r[i+1]=s[1],r[i+2]=s[2],r[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];r[i]=o>>8,r[i+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jp=45,_v=15,xi=new qs;function Uu(t){if(!(t.length>_v))return xi.new(t).parseWith(()=>xi.readIPv4Addr())}function Ku(t){if(!(t.length>Jp))return xi.new(t).parseWith(()=>xi.readIPv6Addr())}function Vs(t){if(!(t.length>Jp))return xi.new(t).parseWith(()=>xi.readIPAddr())}var Z3=parseInt("0xFFFF",16),j3=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var cr=J(Mu(),1);function rm(t){return!!Uu(t)}function nm(t){return!!Ku(t)}function bi(t){return!!Vs(t)}var im=rm,Cv=nm,Fu=function(t){let e=0;if(t=t.toString().trim(),im(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Cv(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let o=im(r[n]),s;o&&(s=Fu(r[n]),r[n]=ee(s.slice(0,2),"base16")),s!=null&&++n<8&&r.splice(n,0,ee(s.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let o=parseInt(r[n],16);i[e++]=o>>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},om=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let o=0;o<r;o++)i.push(t[e+o]);return i.join(".")}if(r===16){let i=[];for(let o=0;o<r;o+=2)i.push(n.getUint16(e+o).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wi={},qu={},Bv=[[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"],[777,-1,"memory"]];Bv.forEach(t=>{let e=Lv(...t);qu[e.code]=e,wi[e.name]=e});function Lv(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function we(t){if(typeof t=="number"){if(qu[t]!=null)return qu[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(wi[t]!=null)return wi[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var kT=we("ip4"),OT=we("ip6"),MT=we("ipcidr");function $u(t,e){switch(we(t).code){case 4:case 41:return Dv(e);case 42:return cm(e);case 6:case 273:case 33:case 132:return lm(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return cm(e);case 421:return Mv(e);case 444:return um(e);case 445:return um(e);case 466:return Ov(e);default:return ee(e,"base16")}}function zu(t,e){switch(we(t).code){case 4:return sm(e);case 41:return sm(e);case 42:return am(e);case 6:case 273:case 33:case 132:return Hu(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return am(e);case 421:return Nv(e);case 444:return Uv(e);case 445:return Kv(e);case 466:return kv(e);default:return Y(e,"base16")}}var Vu=Object.values(kr).map(t=>t.decoder),Pv=function(){let t=Vu[0].or(Vu[1]);return Vu.slice(2).forEach(e=>t=t.or(e)),t}();function sm(t){if(!bi(t))throw new Error("invalid ip address");return Fu(t)}function Dv(t){let e=om(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!bi(e))throw new Error("invalid ip address");return e}function Hu(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function lm(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function am(t){let e=Y(t),r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function cm(t){let e=cr.default.decode(t);if(t=t.slice(cr.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return ee(t)}function Nv(t){let e;t[0]==="Q"||t[0]==="1"?e=ln(Oe.decode(`z${t}`)).bytes:e=Pt.parse(t).multihash.bytes;let r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function kv(t){let e=Pv.decode(t),r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function Ov(t){let e=cr.default.decode(t),r=t.slice(cr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+ee(r,"base64url")}function Mv(t){let e=cr.default.decode(t),r=t.slice(cr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return ee(r,"base58btc")}function Uv(t){let e=t.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 r=mt.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 i=Hu(n);return Me([r,i],r.length+i.length)}function Kv(t){let e=t.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 r=mt.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 i=Hu(n);return Me([r,i],r.length+i.length)}function um(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=ee(e,"base32"),i=lm(r);return`${n}:${i}`}function fm(t){t=Gu(t);let e=[],r=[],n=null,i=t.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<i.length;o++){let s=i[o],a=we(s);if(a.size===0){e.push([a.code]),r.push([a.code]);continue}if(o++,o>=i.length)throw dm("invalid address: "+t);if(a.path===!0){n=Gu(i.slice(o).join("/")),e.push([a.code,zu(a.code,n)]),r.push([a.code,n]);break}let c=zu(a.code,i[o]);e.push([a.code,c]),r.push([a.code,$u(a.code,c)])}return{string:hm(r),bytes:Wu(e),tuples:e,stringTuples:r,path:n}}function Yu(t){let e=[],r=[],n=null,i=0;for(;i<t.length;){let o=Ei.default.decode(t,i),s=Ei.default.decode.bytes??0,a=we(o),c=Fv(a,t.slice(i+s));if(c===0){e.push([o]),r.push([o]),i+=s;continue}let u=t.slice(i+s,i+s+c);if(i+=c+s,i>t.length)throw dm("Invalid address Uint8Array: "+ee(t,"base16"));e.push([o,u]);let l=$u(o,u);if(r.push([o,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(t),string:hm(r),tuples:e,stringTuples:r,path:n}}function hm(t){let e=[];return t.map(r=>{let n=we(r[0]);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Gu(e.join("/"))}function Wu(t){return Me(t.map(e=>{let r=we(e[0]),n=Uint8Array.from(Ei.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=Me([n,e[1]])),n}))}function Fv(t,e){return t.size>0?t.size/8:t.size===0?0:Ei.default.decode(e)+(Ei.default.decode.bytes??0)}function Gu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function dm(t){return new Error("Error parsing address: "+t)}var qv=Symbol.for("nodejs.util.inspect.custom"),Vv=[we("dns").code,we("dns4").code,we("dns6").code,we("dnsaddr").code],Xu=new Map,pm=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Ln(t){return!!t?.[pm]}var Qu=class t{bytes;#e;#t;#r;#n;[pm]=!0;constructor(e){e==null&&(e="");let r;if(e instanceof Uint8Array)r=Yu(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);r=fm(e)}else if(Ln(e))r=Yu(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#e=r.string,this.#t=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,i,o="",s=we("tcp"),a=we("udp"),c=we("ip4"),u=we("ip6"),l=we("dns6"),f=we("ip6zone");for(let[p,d]of this.stringTuples())p===f.code&&(o=`%${d??""}`),Vv.includes(p)&&(r=s.name,i=443,n=`${d??""}${o}`,e=p===l.code?6:4),(p===s.code||p===a.code)&&(r=we(p).name,i=parseInt(d??"")),(p===c.code||p===u.code)&&(r=we(p).name,n=`${d??""}${o}`,e=p===u.code?6:4);if(e==null||r==null||n==null||i==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:r,port:i}}protos(){return this.#t.map(([e])=>Object.assign({},we(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>we(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new t(e),new t(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new t(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new t(Wu(r.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,i])=>{n===wi.p2p.code&&e.push([n,i]),n===wi["p2p-circuit"].code&&(e=[])});let r=e.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?ee(Oe.decode(`z${n}`),"base58btc"):ee(Pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return Le(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(o=>o.resolvable);if(r==null)return[this];let n=Xu.get(r.name);if(n==null)throw new E(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new t(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[qv](){return`Multiaddr(${this.#e})`}};function ze(t){return new Qu(t)}var mm="libp2p-peer-record",ym=Uint8Array.from([3,1]);var po;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=nt((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>rt(o,n.codec()),n.decode=o=>tt(o,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=nt((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos<s;){let a=n.uint32();switch(a>>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),r),t.encode=n=>rt(n,t.codec()),t.decode=n=>tt(n,t.codec())})(po||(po={}));var Pn=class t{static createFromProtobuf=e=>{let r=po.decode(e),n=di(r.peerId),i=(r.addresses??[]).map(s=>ze(s.multiaddr)),o=r.seq;return new t({peerId:n,multiaddrs:i,seqNumber:o})};static DOMAIN=mm;static CODEC=ym;peerId;multiaddrs;seqNumber;domain=t.DOMAIN;codec=t.CODEC;marshaled;constructor(e){let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=po.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof t)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!$p(this.multiaddrs,e.multiaddrs))}};function $v(t){return t[Symbol.asyncIterator]!=null}function zv(t){if($v(t))return(async()=>{let r=[];for await(let n of t)r.push(n);return r})();let e=[];for(let r of t)e.push(r);return e}var mo=zv;var Rm=J(xm(),1);var go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},ju=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},bm=t=>globalThis.DOMException===void 0?new ju(t):new DOMException(t),wm=t=>{let e=t.reason===void 0?bm("This operation was aborted."):t.reason;return e instanceof Error?e:bm(e)};function Ju(t,e,r,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(wm(c)),c.addEventListener("abort",()=>{a(wm(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new go(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{s(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function el(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Dn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Rr,xo=class{constructor(){Rr.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Dn(this,Rr,"f")[this.size-1].priority>=r.priority){Dn(this,Rr,"f").push(n);return}let i=el(Dn(this,Rr,"f"),n,(o,s)=>s.priority-o.priority);Dn(this,Rr,"f").splice(i,0,n)}dequeue(){let e=Dn(this,Rr,"f").shift();return e?.run}filter(e){return Dn(this,Rr,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Dn(this,Rr,"f").length}};Rr=new WeakMap;var Pe=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},q=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ke,wo,Eo,Yr,Qs,vo,zs,$t,bo,wt,Hs,Et,_o,Gr,Gs,Em,vm,Sm,_m,Am,Ys,tl,rl,Xs,Im,Ws,Zs=class extends Error{},zt=class extends Rm.default{constructor(e){var r,n,i,o;if(super(),Ke.add(this),wo.set(this,void 0),Eo.set(this,void 0),Yr.set(this,0),Qs.set(this,void 0),vo.set(this,void 0),zs.set(this,0),$t.set(this,void 0),bo.set(this,void 0),wt.set(this,void 0),Hs.set(this,void 0),Et.set(this,0),_o.set(this,void 0),Gr.set(this,void 0),Gs.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Pe(this,wo,e.carryoverConcurrencyCount,"f"),Pe(this,Eo,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Pe(this,Qs,e.intervalCap,"f"),Pe(this,vo,e.interval,"f"),Pe(this,wt,new e.queueClass,"f"),Pe(this,Hs,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Pe(this,Gs,e.throwOnTimeout===!0,"f"),Pe(this,Gr,e.autoStart===!1,"f")}get concurrency(){return q(this,_o,"f")}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})`);Pe(this,_o,e,"f"),q(this,Ke,"m",Xs).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:q(this,Gs,"f"),...r},new Promise((n,i)=>{q(this,wt,"f").enqueue(async()=>{var o,s,a;Pe(this,Et,(s=q(this,Et,"f"),s++,s),"f"),Pe(this,Yr,(a=q(this,Yr,"f"),a++,a),"f");try{if(!((o=r.signal)===null||o===void 0)&&o.aborted)throw new Zs("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=Ju(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,q(this,Ke,"m",Im).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof go&&!r.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{q(this,Ke,"m",Sm).call(this)}},r),this.emit("add"),q(this,Ke,"m",Ys).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return q(this,Gr,"f")?(Pe(this,Gr,!1,"f"),q(this,Ke,"m",Xs).call(this),this):this}pause(){Pe(this,Gr,!0,"f")}clear(){Pe(this,wt,new(q(this,Hs,"f")),"f")}async onEmpty(){q(this,wt,"f").size!==0&&await q(this,Ke,"m",Ws).call(this,"empty")}async onSizeLessThan(e){q(this,wt,"f").size<e||await q(this,Ke,"m",Ws).call(this,"next",()=>q(this,wt,"f").size<e)}async onIdle(){q(this,Et,"f")===0&&q(this,wt,"f").size===0||await q(this,Ke,"m",Ws).call(this,"idle")}get size(){return q(this,wt,"f").size}sizeBy(e){return q(this,wt,"f").filter(e).length}get pending(){return q(this,Et,"f")}get isPaused(){return q(this,Gr,"f")}};wo=new WeakMap,Eo=new WeakMap,Yr=new WeakMap,Qs=new WeakMap,vo=new WeakMap,zs=new WeakMap,$t=new WeakMap,bo=new WeakMap,wt=new WeakMap,Hs=new WeakMap,Et=new WeakMap,_o=new WeakMap,Gr=new WeakMap,Gs=new WeakMap,Ke=new WeakSet,Em=function(){return q(this,Eo,"f")||q(this,Yr,"f")<q(this,Qs,"f")},vm=function(){return q(this,Et,"f")<q(this,_o,"f")},Sm=function(){var e;Pe(this,Et,(e=q(this,Et,"f"),e--,e),"f"),q(this,Ke,"m",Ys).call(this),this.emit("next")},_m=function(){q(this,Ke,"m",rl).call(this),q(this,Ke,"m",tl).call(this),Pe(this,bo,void 0,"f")},Am=function(){let e=Date.now();if(q(this,$t,"f")===void 0){let r=q(this,zs,"f")-e;if(r<0)Pe(this,Yr,q(this,wo,"f")?q(this,Et,"f"):0,"f");else return q(this,bo,"f")===void 0&&Pe(this,bo,setTimeout(()=>{q(this,Ke,"m",_m).call(this)},r),"f"),!0}return!1},Ys=function(){if(q(this,wt,"f").size===0)return q(this,$t,"f")&&clearInterval(q(this,$t,"f")),Pe(this,$t,void 0,"f"),this.emit("empty"),q(this,Et,"f")===0&&this.emit("idle"),!1;if(!q(this,Gr,"f")){let e=!q(this,Ke,"a",Am);if(q(this,Ke,"a",Em)&&q(this,Ke,"a",vm)){let r=q(this,wt,"f").dequeue();return r?(this.emit("active"),r(),e&&q(this,Ke,"m",tl).call(this),!0):!1}}return!1},tl=function(){q(this,Eo,"f")||q(this,$t,"f")!==void 0||(Pe(this,$t,setInterval(()=>{q(this,Ke,"m",rl).call(this)},q(this,vo,"f")),"f"),Pe(this,zs,Date.now()+q(this,vo,"f"),"f"))},rl=function(){q(this,Yr,"f")===0&&q(this,Et,"f")===0&&q(this,$t,"f")&&(clearInterval(q(this,$t,"f")),Pe(this,$t,void 0,"f")),Pe(this,Yr,q(this,wo,"f")?q(this,Et,"f"):0,"f"),q(this,Ke,"m",Xs).call(this)},Xs=function(){for(;q(this,Ke,"m",Ys).call(this););},Im=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Zs("The task was aborted."))},{once:!0})})},Ws=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var nl=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Cm=t=>globalThis.DOMException===void 0?new il(t):new DOMException(t),Tm=t=>{let e=t.reason===void 0?Cm("This operation was aborted."):t.reason;return e instanceof Error?e:Cm(e)};function ol(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(Tm(h)),h.addEventListener("abort",()=>{l(Tm(h))})}if(r===Number.POSITIVE_INFINITY){t.then(u,l);return}let f=new nl;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${r} milliseconds`,l(f))},r),(async()=>{try{u(await t)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}var sl="lock:worker:request-read",al="lock:worker:release-read",cl="lock:master:grant-read",ul="lock:worker:request-write",ll="lock:worker:release-write",fl="lock:master:grant-write";var Wr={},vi=t=>{t.addEventListener("message",e=>{vi.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{vi.dispatchEvent("message",t,e)})};vi.addEventListener=(t,e)=>{Wr[t]==null&&(Wr[t]=[]),Wr[t].push(e)};vi.removeEventListener=(t,e)=>{Wr[t]!=null&&(Wr[t]=Wr[t].filter(r=>r===e))};vi.dispatchEvent=function(t,e,r){Wr[t]!=null&&Wr[t].forEach(n=>n(e,r))};var hl=vi;var Bm=(t,e,r,n,i)=>(o,s)=>{if(s.data.type!==r)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},Lm=(t,e,r,n)=>async()=>{let i=Ns();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",s)})},Yv={singleProcess:!1},Pm=t=>{if(t=Object.assign({},Yv,t),!!globalThis.document||t.singleProcess){let r=new EventTarget;return hl.addEventListener("message",Bm(r,"requestReadLock",sl,al,cl)),hl.addEventListener("message",Bm(r,"requestWriteLock",ul,ll,fl)),r}return{isWorker:!0,readLock:r=>Lm(r,sl,cl,al),writeLock:r=>Lm(r,ul,fl,ll)}};var Nn={},Qr;async function dl(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await ol((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var Wv=(t,e)=>{if(Qr.isWorker===!0)return{readLock:Qr.readLock(t,e),writeLock:Qr.writeLock(t,e)};let r=new zt({concurrency:1}),n;return{async readLock(){if(n!=null)return await dl(n,e);n=new zt({concurrency:e.concurrency,autoStart:!1});let i=n,o=dl(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await dl(r,e)}}},Qv={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function pl(t){let e=Object.assign({},Qv,t);return Qr==null&&(Qr=Pm(e),Qr.isWorker!==!0&&(Qr.addEventListener("requestReadLock",r=>{Nn[r.data.name]!=null&&Nn[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Qr.addEventListener("requestWriteLock",async r=>{Nn[r.data.name]!=null&&Nn[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),Nn[e.name]==null&&(Nn[e.name]=Wv(e.name,e)),Nn[e.name]}var it={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var _i;(function(t){let e;(function(i){let o;i.codec=()=>(o==null&&(o=nt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=s.bytes();break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>rt(s,i.codec()),i.decode=s=>tt(s,i.codec())})(e=t.Peer$metadataEntry||(t.Peer$metadataEntry={}));let r;(function(i){let o;i.codec=()=>(o==null&&(o=nt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),Js.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=Js.codec().decode(s,s.uint32());break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>rt(s,i.codec()),i.decode=s=>tt(s,i.codec())})(r=t.Peer$tagsEntry||(t.Peer$tagsEntry={}));let n;t.codec=()=>(n==null&&(n=nt((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.addresses!=null)for(let a of i.addresses)o.uint32(10),js.codec().encode(a,o);if(i.protocols!=null)for(let a of i.protocols)o.uint32(18),o.string(a);if(i.publicKey!=null&&(o.uint32(34),o.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())o.uint32(50),t.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())o.uint32(58),t.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.addresses.push(js.codec().decode(i,i.uint32()));break;case 2:s.protocols.push(i.string());break;case 4:s.publicKey=i.bytes();break;case 5:s.peerRecordEnvelope=i.bytes();break;case 6:{let u=t.Peer$metadataEntry.codec().decode(i,i.uint32());s.metadata.set(u.key,u.value);break}case 7:{let u=t.Peer$tagsEntry.codec().decode(i,i.uint32());s.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return s})),n),t.encode=i=>rt(i,t.codec()),t.decode=i=>tt(i,t.codec())})(_i||(_i={}));var js;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.multiaddr!=null&&r.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(js||(js={}));var Js;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.value!=null&&r.value!==0&&(n.uint32(8),n.uint32(r.value)),r.expiry!=null&&(n.uint32(16),n.uint64(r.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={value:0},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.value=r.uint32();break;case 2:i.expiry=r.uint64();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(Js||(Js={}));function Ai(t,e){let r=_i.decode(e);r.publicKey!=null&&t.publicKey==null&&(t=mp({...t,publicKey:t.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[o,s]of r.tags.entries())s.expiry!=null&&s.expiry<i||n.set(o,s);return{...r,id:t,addresses:r.addresses.map(({multiaddr:o,isCertified:s})=>({multiaddr:ze(o),isCertified:s??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}var ml="/peers/";function Si(t){if(!Ds(t)||t.type==null)throw new E("Invalid PeerId",it.ERR_INVALID_PARAMETERS);let e=t.toCID().toString();return new sr(`${ml}${e}`)}async function Dm(t,e,r){let n=new Map;for(let i of r){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=ze(i.multiaddr)),!Ln(i.multiaddr))throw new E("Multiaddr was invalid",it.ERR_INVALID_PARAMETERS);if(!await e(t,i.multiaddr))continue;let o=i.isCertified??!1,s=i.multiaddr.toString(),a=n.get(s);a!=null?i.isCertified=a.isCertified||o:n.set(s,{multiaddr:i.multiaddr,isCertified:o})}return[...n.values()].sort((i,o)=>i.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:i,multiaddr:o})=>({isCertified:i,multiaddr:o.bytes}))}async function ta(t,e,r,n){if(e==null)throw new E("Invalid PeerData",it.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&t.publicKey!=null&&!Le(e.publicKey,t.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",it.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!t.equals(i.id))throw new E("peer id did not match existing peer id",it.ERR_INVALID_PARAMETERS);let o=i?.addresses??[],s=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(r==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ea(f,{validate:Nm})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ea(f,{validate:km,map:Om})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(r==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=ea([...a.entries()],{validate:Nm})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,d]of f)d==null?h.delete(p):h.set(p,d);c=ea([...h.entries()],{validate:km,map:Om})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await Dm(t,n.addressFilter??(async()=>!0),o),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??t.publicKey,peerRecordEnvelope:u};return t.type!=="RSA"&&delete l.publicKey,l}function ea(t,e){let r=new Map;for(let[n,i]of t)i!=null&&e.validate(n,i);for(let[n,i]of t.sort(([o],[s])=>o.localeCompare(s)))i!=null&&r.set(n,e.map?.(n,i)??i);return r}function Nm(t,e){if(typeof t!="string")throw new E("Metadata key must be a string",it.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",it.ERR_INVALID_PARAMETERS)}function km(t,e){if(typeof t!="string")throw new E("Tag name must be a string",it.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",it.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",it.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",it.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",it.ERR_INVALID_PARAMETERS)}}function Om(t,e){let r;return e.expiry!=null&&(r=e.expiry),e.ttl!=null&&(r=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:r}}function ra(t,e,r){let n=t.toString().split("/")[2],i=mt.decode(n),o=di(i),s=r.get(o);if(s!=null)return s;let a=Ai(o,e);return r.set(o,a),a}function Xv(t,e){return t==null?{}:{prefix:ml,filters:(t.filters??[]).map(r=>({key:n,value:i})=>r(ra(n,i,e))),orders:(t.orders??[]).map(r=>(n,i)=>r(ra(n.key,n.value,e),ra(i.key,i.value,e)))}}var na=class{peerId;datastore;lock;addressFilter;constructor(e,r={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=r.addressFilter,this.lock=pl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Si(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",it.ERR_INVALID_PARAMETERS);await this.datastore.delete(Si(e))}async load(e){let r=await this.datastore.get(Si(e));return Ai(e,r)}async save(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,i)}async patch(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,n,i)}async merge(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,n,i)}async*all(e){let r=new qt;for await(let{key:n,value:i}of this.datastore.query(Xv(e??{},r))){let o=ra(n,i,r);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let r=await this.datastore.get(Si(e)),n=Ai(e,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}}async#t(e,r,n,i){let o=_i.encode(r);return n!=null&&Le(o,n)?{peer:Ai(e,o),previous:i,updated:!1}:(await this.datastore.put(Si(e),o),{peer:Ai(e,o),previous:i,updated:!0})}};var _e=ie("libp2p:peer-store"),ia=class{store;events;peerId;constructor(e,r={}){this.events=e.events,this.peerId=e.peerId,this.store=new na(e,r)}async forEach(e,r){_e.trace("forEach await read lock");let n=await this.store.lock.readLock();_e.trace("forEach got read lock");try{for await(let i of this.store.all(r))e(i)}finally{_e.trace("forEach release read lock"),n()}}async all(e){_e.trace("all await read lock");let r=await this.store.lock.readLock();_e.trace("all got read lock");try{return await mo(this.store.all(e))}finally{_e.trace("all release read lock"),r()}}async delete(e){_e.trace("delete await write lock");let r=await this.store.lock.writeLock();_e.trace("delete got write lock");try{await this.store.delete(e)}finally{_e.trace("delete release write lock"),r()}}async has(e){_e.trace("has await read lock");let r=await this.store.lock.readLock();_e.trace("has got read lock");try{return await this.store.has(e)}finally{_e.trace("has release read lock"),r()}}async get(e){_e.trace("get await read lock");let r=await this.store.lock.readLock();_e.trace("get got read lock");try{return await this.store.load(e)}finally{_e.trace("get release read lock"),r()}}async save(e,r){_e.trace("save await write lock");let n=await this.store.lock.writeLock();_e.trace("save got write lock");try{let i=await this.store.save(e,r);return this.#e(e,i),i.peer}finally{_e.trace("save release write lock"),n()}}async patch(e,r){_e.trace("patch await write lock");let n=await this.store.lock.writeLock();_e.trace("patch got write lock");try{let i=await this.store.patch(e,r);return this.#e(e,i),i.peer}finally{_e.trace("patch release write lock"),n()}}async merge(e,r){_e.trace("merge await write lock");let n=await this.store.lock.writeLock();_e.trace("merge got write lock");try{let i=await this.store.merge(e,r);return this.#e(e,i),i.peer}finally{_e.trace("merge release write lock"),n()}}async consumePeerRecord(e,r){let n=await gi.openAndCertify(e,Pn.DOMAIN);if(r?.equals(n.peerId)===!1)return _e("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;let i=Pn.createFromProtobuf(n.payload),o;try{o=await this.get(n.peerId)}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(o?.peerRecordEnvelope!=null){let s=await gi.createFromProtobuf(o.peerRecordEnvelope),a=Pn.createFromProtobuf(s.payload);if(a.seqNumber>=i.seqNumber)return _e("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(s=>({isCertified:!0,multiaddr:s}))}),!0}#e(e,r){r.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))}};function Zv(t){return t[Symbol.asyncIterator]!=null}function jv(t){if(Zv(t))return(async()=>{for await(let e of t);})();for(let e of t);}var yl=jv;function Jv(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var oa=Jv;function e_(t){return t[Symbol.asyncIterator]!=null}function t_(t,e){if(e_(t))return async function*(){for await(let a of t)await e(a)&&(yield a)}();let r=oa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of r)await e(a)&&(yield a)}();let s=e;return function*(){o===!0&&(yield n);for(let a of r)s(a)&&(yield a)}()}var Ht=t_;function r_(t){return t[Symbol.asyncIterator]!=null}function n_(t,e){return r_(t)?async function*(){yield*(await mo(t)).sort(e)}():function*(){yield*mo(t).sort(e)}()}var gl=n_;function i_(t){return t[Symbol.asyncIterator]!=null}function o_(t,e){return i_(t)?async function*(){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}}():function*(){let r=0;if(!(e<1)){for(let n of t)if(yield n,r++,r===e)return}}()}var xl=o_;var sa=class{put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield n}async*getMany(e,r={}){for await(let n of e)yield{key:n,value:await this.get(n,r)}}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await yl(this.putMany(e,n)),e=[],await yl(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null){let i=e.prefix;n=Ht(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Ht(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>gl(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=Ht(n,()=>i++>=o)}return e.limit!=null&&(n=xl(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null){let i=e.prefix;n=Ht(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Ht(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>gl(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=Ht(n,()=>o++>=i)}return e.limit!=null&&(n=xl(n,e.limit)),n}};var Km=J(bl(),1);function Fm(t){return t=t??new Error("Not Found"),(0,Km.default)(t,"ERR_NOT_FOUND")}var aa=class extends sa{data;constructor(){super(),this.data=new Map}put(e,r){return this.data.set(e.toString(),r),e}get(e){let r=this.data.get(e.toString());if(r==null)throw Fm();return r}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,r]of this.data.entries())yield{key:new sr(e),value:r}}*_allKeys(){for(let e of this.data.keys())yield new sr(e)}};function qm(t,e){let r;return function(){let n=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(n,e)}}var c_=ie("libp2p:address-manager"),u_=t=>t;function wl(t,e){let r=t.getPeerId();return r!=null&&pe(r).equals(e)&&(t=t.decapsulate(ze(`/p2p/${e.toString()}`))),t}var ca=class{components;listen;announce;observed;announceFilter;constructor(e,r={}){let{listen:n=[],announce:i=[]}=r;this.components=e,this.listen=n.map(o=>o.toString()),this.announce=new Set(i.map(o=>o.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??u_,this._updatePeerStoreAddresses=qm(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>ze(r))).map(r=>r.getPeerId()===this.components.peerId.toString()?r.decapsulate(`/p2p/${this.components.peerId.toString()}`):r);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(r=>{c_.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(e=>ze(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ze(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ze(e))}addObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString(),i=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString();this.observed.delete(r)}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,i])=>i.confident).map(([n])=>n));let r=new Set(e);return this.announceFilter(Array.from(r).map(n=>ze(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function Vm(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}var El=class{components={};_started=!1;constructor(e={}){this.components={};for(let[r,n]of Object.entries(e))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(r=>Vm(r)).map(async r=>{await r[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")}},l_=["metrics","connectionProtector"],f_=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function $m(t={}){let e=new El(t);return new Proxy(e,{get(n,i,o){if(typeof i=="string"&&!f_.includes(i)){let s=e.components[i];if(s==null&&!l_.includes(i))throw new E(`${i} not set`,"ERR_SERVICE_MISSING");return s}return Reflect.get(n,i,o)},set(n,i,o){return typeof i=="string"?e.components[i]=o:Reflect.set(n,i,o),!0}})}var Xm=J(zm(),1);var Hm="[a-fA-F\\d:]",Xr=t=>t&&t.includeBoundaries?`(?:(?<=\\s|^)(?=${Hm})|(?<=${Hm})(?=\\s|$))`:"",Gt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",qe="[a-fA-F\\d]{1,4}",ua=`
37
+ SELECT points, expire FROM ${this.tableName} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(i=>{i.rowCount===0&&(i=null),r(i)}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this.tableName} WHERE key = $1`,values:[e]}).then(r=>r.rowCount>0):Promise.reject(Error("Table is not created yet"))}};Iy.exports=Pl});var Cy=O(()=>{});var By=O(($6,Ty)=>{Ty.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Py=O((H6,Ly)=>{var O_=By(),Dl=vt();Ly.exports=class{constructor(){this._storage={}}incrby(e,r,n){if(this._storage[e]){let i=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return i!==0?(this._storage[e].value=this._storage[e].value+r,new Dl(0,i,this._storage[e].value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let i=n*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new O_(r,i>0?new Date(Date.now()+i):null),i>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},i),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new Dl(0,i===0?-1:i,this._storage[e].value,!0)}get(e){if(this._storage[e]){let r=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new Dl(0,r,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var kl=O((G6,Ny)=>{var M_=So(),U_=Py(),Dy=vt(),Nl=class extends M_{constructor(e={}){super(e),this._memoryStorage=new U_}consume(e,r=1,n={}){return new Promise((i,o)=>{let s=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(s,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(s,c.consumedPoints,this.blockDuration)),o(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let u=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));u<this.execEvenlyMinDelayMs&&(u=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(i,u,c)}else i(c)})}penalty(e,r=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,r,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}reward(e,r=1,n={}){let i=this.getKey(e);return new Promise(o=>{let s=this._getKeySecDuration(n),a=this._memoryStorage.incrby(i,-r,s);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),o(a)})}block(e,r){let n=r*1e3,i=this.points+1;return this._memoryStorage.set(this.getKey(e),i,r),Promise.resolve(new Dy(0,n===0?-1:n,i))}set(e,r,n){let i=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new Dy(0,i===0?-1:i,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Ny.exports=Nl});var qy=O((Y6,Fy)=>{var ky=Cy(),K_=Vi(),F_=So(),My=kl(),q_=vt(),Tt="rate_limiter_flexible",Li=null,Oy=function(t,e,r,n){let i;n===null||n===!0||n===!1?i=n:i={remainingPoints:n.remainingPoints,msBeforeNext:n.msBeforeNext,consumedPoints:n.consumedPoints,isFirstInDuration:n.isFirstInDuration},t.send({channel:Tt,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:r,data:i})},Uy=function(t){setTimeout(()=>{this._initiated?process.send(t):typeof this._promises[t.promiseId]<"u"&&Uy.call(this,t)},30)},Ti=function(t,e,r,n,i){let o={channel:Tt,keyPrefix:this.keyPrefix,func:t,promiseId:e,data:{key:r,arg:n,opts:i}};this._initiated?process.send(o):Uy.call(this,o)},Ky=function(t,e){if(!e||e.channel!==Tt||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let r;switch(e.func){case"consume":r=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":r=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":r=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":r=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":r=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":r=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}r&&r.then(n=>{Oy(t,e,"resolve",n)}).catch(n=>{Oy(t,e,"reject",n)})},V_=function(t){if(!t||t.channel!==Tt||t.keyPrefix!==this.keyPrefix)return!1;if(this._promises[t.promiseId]){clearTimeout(this._promises[t.promiseId].timeoutId);let e;switch(t.data===null||t.data===!0||t.data===!1?e=t.data:e=new q_(t.data.remainingPoints,t.data.msBeforeNext,t.data.consumedPoints,t.data.isFirstInDuration),t.type){case"resolve":this._promises[t.promiseId].resolve(e);break;case"reject":this._promises[t.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${t.type}'`)}delete this._promises[t.promiseId]}},$_=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},Bi=function(t,e){let r=process.hrtime(),n=r[0].toString()+r[1].toString();return typeof this._promises[n]<"u"&&(n+=K_.randomBytes(12).toString("base64")),this._promises[n]={resolve:t,reject:e,timeoutId:setTimeout(()=>{delete this._promises[n],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},n},Ol=class{constructor(){if(Li)return Li;this._rateLimiters={},ky.setMaxListeners(0),ky.on("message",(e,r)=>{r&&r.channel===Tt&&r.type==="init"?(typeof this._rateLimiters[r.opts.keyPrefix]>"u"&&(this._rateLimiters[r.opts.keyPrefix]=new My(r.opts)),e.send({channel:Tt,type:"init",keyPrefix:r.opts.keyPrefix})):Ky.call(this,e,r)}),Li=this}},Ml=class{constructor(e){if(Li)return Li;this._rateLimiters={},e.launchBus((r,n)=>{n.on("process:msg",i=>{let o=i.raw;if(o&&o.channel===Tt&&o.type==="init")typeof this._rateLimiters[o.opts.keyPrefix]>"u"&&(this._rateLimiters[o.opts.keyPrefix]=new My(o.opts)),e.sendDataToProcessId(i.process.pm_id,{data:{},topic:Tt,channel:Tt,type:"init",keyPrefix:o.opts.keyPrefix},(s,a)=>{s&&console.log(s,a)});else{let s={send:a=>{let c=a;c.topic=Tt,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(i.process.pm_id,c,(u,l)=>{u&&console.log(u,l)})}};Ky.call(this,s,o)}})}),Li=this}},Ul=class extends F_{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",r=>{r&&r.channel===Tt&&r.type==="init"&&r.keyPrefix===this.keyPrefix?this._initiated=!0:V_.call(this,r)}),process.send({channel:Tt,type:"init",opts:$_.call(this)}),this._promises={}}consume(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"consume",s,e,r,n)})}penalty(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"penalty",s,e,r,n)})}reward(e,r=1,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"reward",s,e,r,n)})}block(e,r,n={}){return new Promise((i,o)=>{let s=Bi.call(this,i,o);Ti.call(this,"block",s,e,r,n)})}get(e,r={}){return new Promise((n,i)=>{let o=Bi.call(this,n,i);Ti.call(this,"get",o,e,r)})}delete(e,r={}){return new Promise((n,i)=>{let o=Bi.call(this,n,i);Ti.call(this,"delete",o,e,r)})}};Fy.exports={RateLimiterClusterMaster:Ol,RateLimiterClusterMasterPM2:Ml,RateLimiterCluster:Ul}});var $y=O((W6,Vy)=>{var z_=Ci(),H_=vt(),Kl=class extends z_{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,r,n){let i=new H_;return i.consumedPoints=parseInt(n.consumedPoints),i.isFirstInDuration=n.consumedPoints===r,i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.msBeforeNext=n.msBeforeNext,i}_upsert(e,r,n,i=!1,o={}){return new Promise((s,a)=>{let c=Date.now(),u=Math.floor(n/1e3);i?this.client.set(e,r,u,l=>{l?a(l):this.client.set(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let f={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};s(f)})}):this.client.incr(e,r,(l,f)=>{l||f===!1?this.client.add(e,r,u,(h,p)=>{if(h||!p)if(typeof o.attemptNumber>"u"||o.attemptNumber<3){let d=Object.assign({},o);d.attemptNumber=d.attemptNumber?d.attemptNumber+1:1,this._upsert(e,r,n,i,d).then(m=>s(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,u>0?c+u*1e3:-1,u,()=>{let d={consumedPoints:r,msBeforeNext:u>0?u*1e3:-1};s(d)})}):this.client.get(`${e}_expire`,(h,p)=>{if(h)a(h);else{let d=p===!1?0:p,m={consumedPoints:f,msBeforeNext:d>=0?Math.max(d-c,0):-1};s(m)}})})})}_get(e){return new Promise((r,n)=>{let i=Date.now();this.client.get(e,(o,s)=>{s?this.client.get(`${e}_expire`,(a,c)=>{if(a)n(a);else{let u=c===!1?0:c,l={consumedPoints:s,msBeforeNext:u>=0?Math.max(u-i,0):-1};r(l)}}):r(null)})})}_delete(e){return new Promise((r,n)=>{this.client.del(e,(i,o)=>{i?n(i):o===!1?r(o):this.client.del(`${e}_expire`,s=>{s?n(s):r(o)})})})}};Vy.exports=Kl});var Gy=O((X6,Hy)=>{var zy=vt();Hy.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new zy(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new zy(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,r=1){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.rejectBlack()),typeof n>"u"?this.limiter.consume(e,r):(this.runActionAnyway&&this.limiter.consume(e,r).catch(()=>{}),n)}block(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.block(e,r):(this.runActionAnyway&&this.limiter.block(e,r).catch(()=>{}),n)}penalty(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.penalty(e,r):(this.runActionAnyway&&this.limiter.penalty(e,r).catch(()=>{}),n)}reward(e,r){let n;return this.isWhiteListedSomewhere(e)?n=this.resolveWhite():this.isBlackListedSomewhere(e)&&(n=this.resolveBlack()),typeof n>"u"?this.limiter.reward(e,r):(this.runActionAnyway&&this.limiter.reward(e,r).catch(()=>{}),n)}get(e){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"||this.runActionAnyway?this.limiter.get(e):r}delete(e){return this.limiter.delete(e)}}});var Wy=O((j6,Yy)=>{var G_=So();Yy.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(r=>{if(!(r instanceof G_))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,r=1){return new Promise((n,i)=>{let o=[];this._limiters.forEach(s=>{o.push(s.consume(e,r).catch(a=>({rejected:!0,rej:a})))}),Promise.all(o).then(s=>{let a={},c=!1;s.forEach(u=>{u.rejected===!0&&(c=!0)});for(let u=0;u<s.length;u++)c&&s[u].rejected===!0?a[this._limiters[u].keyPrefix]=s[u].rej:c||(a[this._limiters[u].keyPrefix]=s[u]);c?i(a):n(a)})})}}});var Xy=O((e5,Qy)=>{Qy.exports=class extends Error{constructor(e,r){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,r&&(this.extra=r)}}});var eg=O((r5,Jy)=>{var Zy=Xy(),jy=4294967295,Fl="limiter";Jy.exports=class{constructor(e,r={maxQueueSize:jy}){this._queueLimiters={KEY_DEFAULT:new da(e,r)},this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(e=Fl){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,r=Fl){return this._queueLimiters[r]||(this._queueLimiters[r]=new da(this._limiterFlexible,{key:r,maxQueueSize:this._maxQueueSize})),this._queueLimiters[r].removeTokens(e)}};var da=class{constructor(e,r={maxQueueSize:jy,key:Fl}){this._key=r.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=r.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let r=this;return new Promise((n,i)=>{if(e>r._limiterFlexible.points){i(new Zy(`Requested tokens ${e} exceeds maximum ${r._limiterFlexible.points} tokens per interval`));return}r._queue.length>0?r._queueRequest.call(r,n,i,e):r._limiterFlexible.consume(r._key,e).then(o=>{n(o.remainingPoints)}).catch(o=>{o instanceof Error?i(o):(r._queueRequest.call(r,n,i,e),r._waitTimeout===null&&(r._waitTimeout=setTimeout(r._processFIFO.bind(r),o.msBeforeNext)))})})}_queueRequest(e,r,n){let i=this;i._queue.length<i._maxQueueSize?i._queue.push({resolve:e,reject:r,tokens:n}):r(new Zy(`Number of requests reached it's maximum ${i._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let r=e._queue.shift();e._limiterFlexible.consume(e._key,r.tokens).then(n=>{r.resolve(n.remainingPoints),e._processFIFO.call(e)}).catch(n=>{n instanceof Error?(r.reject(n),e._processFIFO.call(e)):(e._queue.unshift(r),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),n.msBeforeNext)))})}}});var rg=O((i5,tg)=>{var ql=vt();tg.exports=class{constructor(e,r){this._rateLimiter=e,this._burstLimiter=r}_combineRes(e,r){return e?new ql(e.remainingPoints,Math.min(e.msBeforeNext,r?r.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,r=1,n={}){return this._rateLimiter.consume(e,r,n).catch(i=>i instanceof ql?this._burstLimiter.consume(e,r,n).then(o=>Promise.resolve(this._combineRes(i,o))).catch(o=>o instanceof ql?Promise.reject(this._combineRes(i,o)):Promise.reject(o)):Promise.reject(i))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([r,n])=>this._combineRes(r,n))}get points(){return this._rateLimiter.points}}});var ig=O((o5,ng)=>{var Y_=wy(),W_=_y(),Q_=Sy(),X_=Ry(),{RateLimiterClusterMaster:Z_,RateLimiterClusterMasterPM2:j_,RateLimiterCluster:J_}=qy(),eA=kl(),tA=$y(),rA=Gy(),nA=Wy(),iA=eg(),oA=rg(),sA=vt();ng.exports={RateLimiterRedis:Y_,RateLimiterMongo:W_,RateLimiterMySQL:Q_,RateLimiterPostgres:X_,RateLimiterMemory:eA,RateLimiterMemcache:tA,RateLimiterClusterMaster:Z_,RateLimiterClusterMasterPM2:j_,RateLimiterCluster:J_,RLWrapperBlackAndWhite:rA,RateLimiterUnion:nA,RateLimiterQueue:iA,BurstyRateLimiter:oA,RateLimiterRes:sA}});var KA={};He(KA,{createLibp2p:()=>UA});var vg=J($n(),1);var M8=J(qi(),1),U8=J(H0(),1);var Wn=class t extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.code=t.code,this.type=t.type}static code="ABORT_ERR";static type="aborted"},E=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var Ts=J(ye(),1);function cn(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var uc={};He(uc,{identity:()=>b2});function p2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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,x=d.length;g!==x&&d[g]===0;)g++,m++;for(var w=(x-g)*l+1>>>0,C=new Uint8Array(w);g!==x;){for(var _=d[g],A=0,P=w-1;(_!==0||A<y)&&P!==-1;P--,A++)_+=256*C[P]>>>0,C[P]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}for(var D=w-y;D!==w&&C[D]===0;)D++;for(var W=c.repeat(m);D<w;++D)W+=t.charAt(C[D]);return W}function h(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 x=(d.length-m)*u+1>>>0,w=new Uint8Array(x);d[m];){var C=r[d.charCodeAt(m)];if(C===255)return;for(var _=0,A=x-1;(C!==0||_<g)&&A!==-1;A--,_++)C+=a*w[A]>>>0,w[A]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=_,m++}if(d[m]!==" "){for(var P=x-g;P!==x&&w[P]===0;)P++;for(var D=new Uint8Array(y+(x-P)),W=y;P!==x;)D[W++]=w[P++];return D}}}function p(d){var m=h(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var m2=p2,y2=m2,G0=y2;var yS=new Uint8Array(0);var Y0=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},pr=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var W0=t=>new TextEncoder().encode(t),Q0=t=>new TextDecoder().decode(t);var oc=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},sc=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.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 Z0(this,e)}},ac=class{constructor(e){this.decoders=e}or(e){return Z0(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Z0=(t,e)=>new ac({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),cc=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new oc(e,r,n),this.decoder=new sc(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Qn=({name:t,prefix:e,encode:r,decode:n})=>new cc(t,e,r,n),Dr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=G0(r,e);return Qn({prefix:t,name:e,encode:n,decode:o=>pr(i(o))})},g2=(t,e,r,n)=>{let i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let l=0;l<o;++l){let f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},x2=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>r;)s-=r,o+=e[i&a>>s];if(s&&(o+=e[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Ne=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Qn({prefix:e,name:t,encode(i){return x2(i,n,r)},decode(i){return g2(i,n,r,t)}});var b2=Qn({prefix:"\0",name:"identity",encode:t=>Q0(t),decode:t=>W0(t)});var lc={};He(lc,{base2:()=>w2});var w2=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fc={};He(fc,{base8:()=>E2});var E2=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hc={};He(hc,{base10:()=>v2});var v2=Dr({prefix:"9",name:"base10",alphabet:"0123456789"});var dc={};He(dc,{base16:()=>_2,base16upper:()=>A2});var _2=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A2=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pc={};He(pc,{base32:()=>mt,base32hex:()=>C2,base32hexpad:()=>B2,base32hexpadupper:()=>L2,base32hexupper:()=>T2,base32pad:()=>I2,base32padupper:()=>R2,base32upper:()=>S2,base32z:()=>P2});var mt=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),S2=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),I2=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R2=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),C2=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),T2=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),B2=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L2=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),P2=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mc={};He(mc,{base36:()=>D2,base36upper:()=>N2});var D2=Dr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),N2=Dr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yc={};He(yc,{base58btc:()=>Oe,base58flickr:()=>k2});var Oe=Dr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),k2=Dr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var gc={};He(gc,{base64:()=>un,base64pad:()=>O2,base64url:()=>M2,base64urlpad:()=>U2});var un=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O2=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),M2=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U2=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xc={};He(xc,{base256emoji:()=>$2});var j0=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}"),K2=j0.reduce((t,e,r)=>(t[r]=e,t),[]),F2=j0.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function q2(t){return t.reduce((e,r)=>(e+=K2[r],e),"")}function V2(t){let e=[];for(let r of t){let n=F2[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var $2=Qn({prefix:"\u{1F680}",name:"base256emoji",encode:q2,decode:V2});var vc={};He(vc,{sha256:()=>et,sha512:()=>cb});var z2=th,J0=128,H2=127,G2=~H2,Y2=Math.pow(2,31);function th(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Y2;)e[r++]=t&255|J0,t/=128;for(;t&G2;)e[r++]=t&255|J0,t>>>=7;return e[r]=t|0,th.bytes=r-n+1,e}var W2=bc,Q2=128,eh=127;function bc(t,n){var r=0,n=n||0,i=0,o=n,s,a=t.length;do{if(o>=a)throw bc.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&eh)<<i:(s&eh)*Math.pow(2,i),i+=7}while(s>=Q2);return bc.bytes=o-n,r}var X2=Math.pow(2,7),Z2=Math.pow(2,14),j2=Math.pow(2,21),J2=Math.pow(2,28),eb=Math.pow(2,35),tb=Math.pow(2,42),rb=Math.pow(2,49),nb=Math.pow(2,56),ib=Math.pow(2,63),ob=function(t){return t<X2?1:t<Z2?2:t<j2?3:t<J2?4:t<eb?5:t<tb?6:t<rb?7:t<nb?8:t<ib?9:10},sb={encode:z2,decode:W2,encodingLength:ob},ab=sb,Hi=ab;var Gi=(t,e=0)=>[Hi.decode(t,e),Hi.decode.bytes],Xn=(t,e,r=0)=>(Hi.encode(t,e,r),e),Zn=t=>Hi.encodingLength(t);var Jt=(t,e)=>{let r=e.byteLength,n=Zn(t),i=n+Zn(r),o=new Uint8Array(i+r);return Xn(t,o,0),Xn(r,o,n),o.set(e,i),new jn(t,r,e,o)},ln=t=>{let e=pr(t),[r,n]=Gi(e),[i,o]=Gi(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new jn(r,i,s,e)},rh=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Y0(t.bytes,r.bytes)}},jn=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var Ec=({name:t,code:e,encode:r})=>new wc(t,e,r),wc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Jt(this.code,r):r.then(n=>Jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};var ih=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),et=Ec({name:"sha2-256",code:18,encode:ih("SHA-256")}),cb=Ec({name:"sha2-512",code:19,encode:ih("SHA-512")});var _c={};He(_c,{identity:()=>Nr});var oh=0,ub="identity",sh=pr,lb=t=>Jt(oh,sh(t)),Nr={code:oh,name:ub,encode:sh,digest:lb};var MS=new TextEncoder,US=new TextDecoder;var ah=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return pb(r,Ac(t),e||Oe.encoder);default:return mb(r,Ac(t),e||mt.encoder)}};var ch=new WeakMap,Ac=t=>{let e=ch.get(t);if(e==null){let r=new Map;return ch.set(t,r),r}return e},Pt=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:r}=this;if(e!==Yi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yb)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Jt(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&rh(e.multihash,n.multihash)}toString(e){return ah(this,e)}toJSON(){return{"/":ah(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s||uh(n,i,o.bytes))}else if(r[gb]===!0){let{version:n,multihash:i,code:o}=r,s=ln(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="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(r!==Yi)throw new Error(`Version 0 CID must use dag-pb (code: ${Yi}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=uh(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Yi,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=pr(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new jn(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=Gi(e.subarray(r));return r+=h,f},i=n(),o=Yi;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,l=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,i]=db(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ac(o).set(n,e),o}},db=(t,e)=>{switch(t[0]){case"Q":{let r=e||Oe;return[Oe.prefix,r.decode(`${Oe.prefix}${t}`)]}case Oe.prefix:{let r=e||Oe;return[Oe.prefix,r.decode(t)]}case mt.prefix:{let r=e||mt;return[mt.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},pb=(t,e,r)=>{let{prefix:n}=r;if(n!==Oe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i},mb=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i},Yi=112,yb=18,uh=(t,e,r)=>{let n=Zn(t),i=n+Zn(e),o=new Uint8Array(i+r.byteLength);return Xn(t,o,0),Xn(e,o,n),o.set(r,i),o},gb=Symbol.for("@ipld/js-cid/CID");var kr={...uc,...lc,...fc,...hc,...dc,...pc,...mc,...yc,...gc,...xc},WS={...vc,..._c};function mr(t=0){return globalThis.Buffer?.alloc!=null?cn(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function Dt(t=0){return globalThis.Buffer?.allocUnsafe!=null?cn(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var lh=fh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Sc=fh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Dt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),xb={utf8:lh,"utf-8":lh,hex:kr.base16,latin1:Sc,ascii:Sc,binary:Sc,...kr},is=xb;function Y(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?cn(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var au={};He(au,{Ed25519PrivateKey:()=>xn,Ed25519PublicKey:()=>Ji,generateKeyPair:()=>Kw,generateKeyPairFromSeed:()=>Id,unmarshalEd25519PrivateKey:()=>Mw,unmarshalEd25519PublicKey:()=>Uw});function Le(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ic(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function bb(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}function hh(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function wb(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ic(t.outputLen),Ic(t.blockLen)}function Eb(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vb(t,e){hh(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var _b={number:Ic,bool:bb,bytes:hh,hash:wb,exists:Eb,output:vb},yr=_b;var os=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var dh=t=>t instanceof Uint8Array;var ss=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Nt=(t,e)=>t<<32-e|t>>>e,Ab=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ab)throw new Error("Non little-endian hardware is not supported");var cI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rc(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Wi(t){if(typeof t=="string"&&(t=Rc(t)),!dh(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function as(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;return t.forEach(n=>{if(!dh(n))throw new Error("Uint8Array expected");e.set(n,r),r+=n.length}),e}var Jn=class{clone(){return this._cloneInto()}};function Or(t){let e=n=>t().update(Wi(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function hn(t=32){if(os&&typeof os.getRandomValues=="function")return os.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Sb(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;t.setUint32(e+c,s,n),t.setUint32(e+u,a,n)}var ei=class extends Jn{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ss(this.buffer)}update(e){yr.exists(this);let{view:r,buffer:n,blockLen:i}=this;e=Wi(e);let o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=ss(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){yr.exists(this),yr.output(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;Sb(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=ss(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.length=i,e.pos=a,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var cs=BigInt(4294967295),Cc=BigInt(32);function ph(t,e=!1){return e?{h:Number(t&cs),l:Number(t>>Cc&cs)}:{h:Number(t>>Cc&cs)|0,l:Number(t&cs)|0}}function Ib(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=ph(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var Rb=(t,e)=>BigInt(t>>>0)<<Cc|BigInt(e>>>0),Cb=(t,e,r)=>t>>>r,Tb=(t,e,r)=>t<<32-r|e>>>r,Bb=(t,e,r)=>t>>>r|e<<32-r,Lb=(t,e,r)=>t<<32-r|e>>>r,Pb=(t,e,r)=>t<<64-r|e>>>r-32,Db=(t,e,r)=>t>>>r-32|e<<64-r,Nb=(t,e)=>e,kb=(t,e)=>t,Ob=(t,e,r)=>t<<r|e>>>32-r,Mb=(t,e,r)=>e<<r|t>>>32-r,Ub=(t,e,r)=>e<<r-32|t>>>64-r,Kb=(t,e,r)=>t<<r-32|e>>>64-r;function Fb(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var qb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Vb=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,$b=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),zb=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,Hb=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Gb=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0,Yb={fromBig:ph,split:Ib,toBig:Rb,shrSH:Cb,shrSL:Tb,rotrSH:Bb,rotrSL:Lb,rotrBH:Pb,rotrBL:Db,rotr32H:Nb,rotr32L:kb,rotlSH:Ob,rotlSL:Mb,rotlBH:Ub,rotlBL:Kb,add:Fb,add3L:qb,add3H:Vb,add4L:$b,add4H:zb,add5H:Gb,add5L:Hb},j=Yb;var[Wb,Qb]=j.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(t=>BigInt(t))),Mr=new Uint32Array(80),Ur=new Uint32Array(80),ti=class extends ei{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:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:p,Gl:d,Hh:m,Hl:y}=this;return[e,r,n,i,o,s,a,c,u,l,f,h,p,d,m,y]}set(e,r,n,i,o,s,a,c,u,l,f,h,p,d,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=d|0,this.Hh=m|0,this.Hl=y|0}process(e,r){for(let w=0;w<16;w++,r+=4)Mr[w]=e.getUint32(r),Ur[w]=e.getUint32(r+=4);for(let w=16;w<80;w++){let C=Mr[w-15]|0,_=Ur[w-15]|0,A=j.rotrSH(C,_,1)^j.rotrSH(C,_,8)^j.shrSH(C,_,7),P=j.rotrSL(C,_,1)^j.rotrSL(C,_,8)^j.shrSL(C,_,7),D=Mr[w-2]|0,W=Ur[w-2]|0,Q=j.rotrSH(D,W,19)^j.rotrBH(D,W,61)^j.shrSH(D,W,6),H=j.rotrSL(D,W,19)^j.rotrBL(D,W,61)^j.shrSL(D,W,6),ne=j.add4L(P,H,Ur[w-7],Ur[w-16]),ge=j.add4H(ne,A,Q,Mr[w-7],Mr[w-16]);Mr[w]=ge|0,Ur[w]=ne|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:p,Fl:d,Gh:m,Gl:y,Hh:g,Hl:x}=this;for(let w=0;w<80;w++){let C=j.rotrSH(f,h,14)^j.rotrSH(f,h,18)^j.rotrBH(f,h,41),_=j.rotrSL(f,h,14)^j.rotrSL(f,h,18)^j.rotrBL(f,h,41),A=f&p^~f&m,P=h&d^~h&y,D=j.add5L(x,_,P,Qb[w],Ur[w]),W=j.add5H(D,g,C,A,Wb[w],Mr[w]),Q=D|0,H=j.rotrSH(n,i,28)^j.rotrBH(n,i,34)^j.rotrBH(n,i,39),ne=j.rotrSL(n,i,28)^j.rotrBL(n,i,34)^j.rotrBL(n,i,39),ge=n&o^n&a^o&a,Ze=i&s^i&c^s&c;g=m|0,x=y|0,m=p|0,y=d|0,p=f|0,d=h|0,{h:f,l:h}=j.add(u|0,l|0,W|0,Q|0),u=a|0,l=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let T=j.add3L(Q,ne,Ze);n=j.add3H(T,W,H,ge),i=T|0}({h:n,l:i}=j.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=j.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=j.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=j.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:d}=j.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:m,l:y}=j.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:g,l:x}=j.add(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,i,o,s,a,c,u,l,f,h,p,d,m,y,g,x)}roundClean(){Mr.fill(0),Ur.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)}},Tc=class extends ti{constructor(){super(),this.Ah=-1942145080,this.Al=424955298,this.Bh=1944164710,this.Bl=-1982016298,this.Ch=502970286,this.Cl=855612546,this.Dh=1738396948,this.Dl=1479516111,this.Eh=258812777,this.El=2077511080,this.Fh=2011393907,this.Fl=79989058,this.Gh=1067287976,this.Gl=1780299464,this.Hh=286451373,this.Hl=-1848208735,this.outputLen=28}},Bc=class extends ti{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}},Lc=class extends ti{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}},Pc=Or(()=>new ti),gI=Or(()=>new Tc),xI=Or(()=>new Bc),bI=Or(()=>new Lc);var fs={};He(fs,{bitGet:()=>ew,bitLen:()=>Jb,bitMask:()=>Qi,bitSet:()=>tw,bytesToHex:()=>er,bytesToNumberBE:()=>kt,bytesToNumberLE:()=>tr,concatBytes:()=>Ot,createHmacDrbg:()=>kc,ensureBytes:()=>ve,equalBytes:()=>xh,hexToBytes:()=>dn,hexToNumber:()=>Nc,numberToBytesBE:()=>gr,numberToBytesLE:()=>Kr,numberToHexUnpadded:()=>gh,numberToVarBytesBE:()=>jb,utf8ToBytes:()=>bh,validateObject:()=>It});var yh=BigInt(0),us=BigInt(1),Xb=BigInt(2),ls=t=>t instanceof Uint8Array,Zb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function er(t){if(!ls(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Zb[t[r]];return e}function gh(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Nc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function dn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(e/2);for(let n=0;n<r.length;n++){let i=n*2,o=t.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");r[n]=s}return r}function kt(t){return Nc(er(t))}function tr(t){if(!ls(t))throw new Error("Uint8Array expected");return Nc(er(Uint8Array.from(t).reverse()))}function gr(t,e){return dn(t.toString(16).padStart(e*2,"0"))}function Kr(t,e){return gr(t,e).reverse()}function jb(t){return dn(gh(t))}function ve(t,e,r){let n;if(typeof e=="string")try{n=dn(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(ls(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function Ot(...t){let e=new Uint8Array(t.reduce((n,i)=>n+i.length,0)),r=0;return t.forEach(n=>{if(!ls(n))throw new Error("Uint8Array expected");e.set(n,r),r+=n.length}),e}function xh(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function bh(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Jb(t){let e;for(e=0;t>yh;t>>=us,e+=1);return e}function ew(t,e){return t>>BigInt(e)&us}var tw=(t,e,r)=>t|(r?us:yh)<<BigInt(e),Qi=t=>(Xb<<BigInt(t-1))-us,Dc=t=>new Uint8Array(t),mh=t=>Uint8Array.from(t);function kc(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=Dc(t),i=Dc(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...f)=>r(i,n,...f),c=(f=Dc())=>{i=a(mh([0]),f),n=a(),f.length!==0&&(i=a(mh([1]),f),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=a();let p=n.slice();h.push(p),f+=n.length}return Ot(...h)};return(f,h)=>{s(),c(f);let p;for(;!(p=h(u()));)c();return s(),p}}var rw={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function It(t,e,r={}){let n=(i,o,s)=>{let a=rw[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);let c=t[i];if(!(s&&c===void 0)&&!a(c,t))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var $e=BigInt(0),Re=BigInt(1),pn=BigInt(2),nw=BigInt(3),Oc=BigInt(4),wh=BigInt(5),Eh=BigInt(8),iw=BigInt(9),ow=BigInt(16);function de(t,e){let r=t%e;return r>=$e?r:e+r}function vh(t,e,r){if(r<=$e||e<$e)throw new Error("Expected power/modulo > 0");if(r===Re)return $e;let n=Re;for(;e>$e;)e&Re&&(n=n*t%r),t=t*t%r,e>>=Re;return n}function Ce(t,e,r){let n=t;for(;e-- >$e;)n*=n,n%=r;return n}function hs(t,e){if(t===$e||e<=$e)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=de(t,e),n=e,i=$e,o=Re,s=Re,a=$e;for(;r!==$e;){let u=n/r,l=n%r,f=i-s*u,h=o-a*u;n=r,r=l,i=s,o=a,s=f,a=h}if(n!==Re)throw new Error("invert: does not exist");return de(i,e)}function sw(t){let e=(t-Re)/pn,r,n,i;for(r=t-Re,n=0;r%pn===$e;r/=pn,n++);for(i=pn;i<t&&vh(i,e,t)!==t-Re;i++);if(n===1){let s=(t+Re)/Oc;return function(c,u){let l=c.pow(u,s);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let o=(r+Re)/pn;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,i),r),f=a.pow(c,o),h=a.pow(c,r);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let p=1;for(let m=a.sqr(h);p<u&&!a.eql(m,a.ONE);p++)m=a.sqr(m);let d=a.pow(l,Re<<BigInt(u-p-1));l=a.sqr(d),f=a.mul(f,d),h=a.mul(h,l),u=p}return f}}function aw(t){if(t%Oc===nw){let e=(t+Re)/Oc;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%Eh===wh){let e=(t-wh)/Eh;return function(n,i){let o=n.mul(i,pn),s=n.pow(o,e),a=n.mul(i,s),c=n.mul(n.mul(a,pn),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%ow,sw(t)}var _h=(t,e)=>(de(t,e)&Re)===Re,cw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mc(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=cw.reduce((n,i)=>(n[i]="function",n),e);return It(t,r)}function uw(t,e,r){if(r<$e)throw new Error("Expected power > 0");if(r===$e)return t.ONE;if(r===Re)return e;let n=t.ONE,i=e;for(;r>$e;)r&Re&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Re;return n}function lw(t,e){let r=new Array(e.length),n=e.reduce((o,s,a)=>t.is0(s)?o:(r[a]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,a)=>t.is0(s)?o:(r[a]=t.mul(o,r[a]),t.mul(o,s)),i),r}function ds(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ps(t,e,r=!1,n={}){if(t<=$e)throw new Error(`Expected Fp ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=ds(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=aw(t),a=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Qi(i),ZERO:$e,ONE:Re,create:c=>de(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return $e<=c&&c<t},is0:c=>c===$e,isOdd:c=>(c&Re)===Re,neg:c=>de(-c,t),eql:(c,u)=>c===u,sqr:c=>de(c*c,t),add:(c,u)=>de(c+u,t),sub:(c,u)=>de(c-u,t),mul:(c,u)=>de(c*u,t),pow:(c,u)=>uw(a,c,u),div:(c,u)=>de(c*hs(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>hs(c,t),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>lw(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Kr(c,o):gr(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return r?tr(c):kt(c)}});return Object.freeze(a)}function Ah(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function Sh(t,e,r=!1){t=ve("privateHash",t);let n=t.length,i=ds(e).nByteLength+8;if(i<24||n<i||n>1024)throw new Error(`hashToPrivateScalar: expected ${i}-1024 bytes of input, got ${n}`);let o=r?tr(t):kt(t);return de(o,e-Re)+Re}var hw=BigInt(0),Uc=BigInt(1);function ms(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,a=i;for(;o>hw;)o&Uc&&(s=s.add(a)),a=a.double(),o>>=Uc;return s},precomputeWindow(i,o){let{windows:s,windowSize:a}=n(o),c=[],u=i,l=u;for(let f=0;f<s;f++){l=u,c.push(l);for(let h=1;h<a;h++)l=l.add(u),c.push(l);u=l.double()}return c},wNAF(i,o,s){let{windows:a,windowSize:c}=n(i),u=t.ZERO,l=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let d=0;d<a;d++){let m=d*c,y=Number(s&f);s>>=p,y>c&&(y-=h,s+=Uc);let g=m,x=m+Math.abs(y)-1,w=d%2!==0,C=y<0;y===0?l=l.add(r(w,o[g])):u=u.add(r(C,o[x]))}return{p:u,f:l}},wNAFCached(i,o,s,a){let c=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&o.set(i,a(u))),this.wNAF(c,u,s)}}}function Xi(t){return Mc(t.Fp),It(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ds(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}var Mt=BigInt(0),yt=BigInt(1),ys=BigInt(2),dw=BigInt(8),pw={zip215:!0};function mw(t){let e=Xi(t);return It(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function gs(t){let e=mw(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:a,h:c}=e,u=ys<<BigInt(a*8)-yt,l=r.create,f=e.uvRatio||((N,I)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(I))}}catch{return{isValid:!1,value:Mt}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,I,K)=>{if(I.length||K)throw new Error("Contexts/pre-hash are not supported");return N}),d=N=>typeof N=="bigint"&&Mt<N,m=(N,I)=>d(N)&&d(I)&&N<I,y=N=>N===Mt||m(N,u);function g(N,I){if(m(N,I))return N;throw new Error(`Expected valid scalar < ${I}, got ${typeof N} ${N}`)}function x(N){return N===Mt?N:g(N,n)}let w=new Map;function C(N){if(!(N instanceof _))throw new Error("ExtendedPoint expected")}class _{constructor(I,K,V,G){if(this.ex=I,this.ey=K,this.ez=V,this.et=G,!y(I))throw new Error("x required");if(!y(K))throw new Error("y required");if(!y(V))throw new Error("z required");if(!y(G))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(I){if(I instanceof _)throw new Error("extended point not allowed");let{x:K,y:V}=I||{};if(!y(K)||!y(V))throw new Error("invalid affine point");return new _(K,V,yt,l(K*V))}static normalizeZ(I){let K=r.invertBatch(I.map(V=>V.ez));return I.map((V,G)=>V.toAffine(K[G])).map(_.fromAffine)}_setWindowSize(I){this._WINDOW_SIZE=I,w.delete(this)}assertValidity(){let{a:I,d:K}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:V,ey:G,ez:te,et:oe}=this,me=l(V*V),se=l(G*G),fe=l(te*te),Fe=l(fe*fe),De=l(me*I),je=l(fe*l(De+se)),Je=l(Fe+l(K*l(me*se)));if(je!==Je)throw new Error("bad point: equation left != right (1)");let Ve=l(V*G),st=l(te*oe);if(Ve!==st)throw new Error("bad point: equation left != right (2)")}equals(I){C(I);let{ex:K,ey:V,ez:G}=this,{ex:te,ey:oe,ez:me}=I,se=l(K*me),fe=l(te*G),Fe=l(V*me),De=l(oe*G);return se===fe&&Fe===De}is0(){return this.equals(_.ZERO)}negate(){return new _(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:I}=e,{ex:K,ey:V,ez:G}=this,te=l(K*K),oe=l(V*V),me=l(ys*l(G*G)),se=l(I*te),fe=K+V,Fe=l(l(fe*fe)-te-oe),De=se+oe,je=De-me,Je=se-oe,Ve=l(Fe*je),st=l(De*Je),lr=l(Fe*Je),tn=l(je*De);return new _(Ve,st,tn,lr)}add(I){C(I);let{a:K,d:V}=e,{ex:G,ey:te,ez:oe,et:me}=this,{ex:se,ey:fe,ez:Fe,et:De}=I;if(K===BigInt(-1)){let df=l((te-G)*(fe+se)),pf=l((te+G)*(fe-se)),ka=l(pf-df);if(ka===Mt)return this.double();let mf=l(oe*ys*De),yf=l(me*ys*Fe),gf=yf+mf,xf=pf+df,bf=yf-mf,Cg=l(gf*ka),Tg=l(xf*bf),Bg=l(gf*bf),Lg=l(ka*xf);return new _(Cg,Tg,Lg,Bg)}let je=l(G*se),Je=l(te*fe),Ve=l(me*V*De),st=l(oe*Fe),lr=l((G+te)*(se+fe)-je-Je),tn=st-Ve,Mi=st+Ve,hf=l(Je-K*je),Ag=l(lr*tn),Sg=l(Mi*hf),Ig=l(lr*hf),Rg=l(tn*Mi);return new _(Ag,Sg,Rg,Ig)}subtract(I){return this.add(I.negate())}wNAF(I){return D.wNAFCached(this,w,I,_.normalizeZ)}multiply(I){let{p:K,f:V}=this.wNAF(g(I,n));return _.normalizeZ([K,V])[0]}multiplyUnsafe(I){let K=x(I);return K===Mt?P:this.equals(P)||K===yt?this:this.equals(A)?this.wNAF(K).p:D.unsafeLadder(this,K)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(I){let{ex:K,ey:V,ez:G}=this,te=this.is0();I==null&&(I=te?dw:r.inv(G));let oe=l(K*I),me=l(V*I),se=l(G*I);if(te)return{x:Mt,y:yt};if(se!==yt)throw new Error("invZ was invalid");return{x:oe,y:me}}clearCofactor(){let{h:I}=e;return I===yt?this:this.multiplyUnsafe(I)}static fromHex(I,K=!1){let{d:V,a:G}=e,te=r.BYTES;I=ve("pointHex",I,te);let oe=I.slice(),me=I[te-1];oe[te-1]=me&-129;let se=tr(oe);se===Mt||(K?g(se,u):g(se,r.ORDER));let fe=l(se*se),Fe=l(fe-yt),De=l(V*fe-G),{isValid:je,value:Je}=f(Fe,De);if(!je)throw new Error("Point.fromHex: invalid y coordinate");let Ve=(Je&yt)===yt,st=(me&128)!==0;if(!K&&Je===Mt&&st)throw new Error("Point.fromHex: x=0 and x_0=1");return st!==Ve&&(Je=l(-Je)),_.fromAffine({x:Je,y:se})}static fromPrivateKey(I){return H(I).point}toRawBytes(){let{x:I,y:K}=this.toAffine(),V=Kr(K,r.BYTES);return V[V.length-1]|=I&yt?128:0,V}toHex(){return er(this.toRawBytes())}}_.BASE=new _(e.Gx,e.Gy,yt,l(e.Gx*e.Gy)),_.ZERO=new _(Mt,yt,yt,Mt);let{BASE:A,ZERO:P}=_,D=ms(_,a*8);function W(N){return de(N,n)}function Q(N){return W(tr(N))}function H(N){let I=a;N=ve("private key",N,I);let K=ve("hashed private key",o(N),2*I),V=h(K.slice(0,I)),G=K.slice(I,2*I),te=Q(V),oe=A.multiply(te),me=oe.toRawBytes();return{head:V,prefix:G,scalar:te,point:oe,pointBytes:me}}function ne(N){return H(N).pointBytes}function ge(N=new Uint8Array,...I){let K=Ot(...I);return Q(o(p(K,ve("context",N),!!i)))}function Ze(N,I,K={}){N=ve("message",N),i&&(N=i(N));let{prefix:V,scalar:G,pointBytes:te}=H(I),oe=ge(K.context,V,N),me=A.multiply(oe).toRawBytes(),se=ge(K.context,me,te,N),fe=W(oe+se*G);x(fe);let Fe=Ot(me,Kr(fe,r.BYTES));return ve("result",Fe,a*2)}let T=pw;function k(N,I,K,V=T){let{context:G,zip215:te}=V,oe=r.BYTES;N=ve("signature",N,2*oe),I=ve("message",I),i&&(I=i(I));let me=tr(N.slice(oe,2*oe)),se,fe,Fe;try{se=_.fromHex(K,te),fe=_.fromHex(N.slice(0,oe),te),Fe=A.multiplyUnsafe(me)}catch{return!1}if(!te&&se.isSmallOrder())return!1;let De=ge(G,fe.toRawBytes(),se.toRawBytes(),I);return fe.add(se.multiplyUnsafe(De)).subtract(Fe).clearCofactor().equals(_.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:ne,sign:Ze,verify:k,ExtendedPoint:_,utils:{getExtendedPublicKey:H,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,I=_.BASE){return I._setWindowSize(N),I.multiply(BigInt(3)),I}}}}var LI=BigInt(0),PI=BigInt(1);var Fc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ih=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GI=BigInt(0),gw=BigInt(1),Kc=BigInt(2),xw=BigInt(5),Rh=BigInt(10),bw=BigInt(20),ww=BigInt(40),Ch=BigInt(80);function Ew(t){let e=Fc,n=t*t%e*t%e,i=Ce(n,Kc,e)*n%e,o=Ce(i,gw,e)*t%e,s=Ce(o,xw,e)*o%e,a=Ce(s,Rh,e)*s%e,c=Ce(a,bw,e)*a%e,u=Ce(c,ww,e)*c%e,l=Ce(u,Ch,e)*u%e,f=Ce(l,Ch,e)*u%e,h=Ce(f,Rh,e)*s%e;return{pow_p_5_8:Ce(h,Kc,e)*t%e,b2:n}}function vw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function _w(t,e){let r=Fc,n=de(e*e*e,r),i=de(n*n*e,r),o=Ew(t*i).pow_p_5_8,s=de(t*n*o,r),a=de(e*s*s,r),c=s,u=de(s*Ih,r),l=a===t,f=a===de(-t,r),h=a===de(-t*Ih,r);return l&&(s=c),(f||h)&&(s=u),_h(s,r)&&(s=de(-s,r)),{isValid:l||f,value:s}}var xr=ps(Fc,void 0,!0),qc={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:xr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Pc,randomBytes:hn,adjustScalarBytes:vw,uvRatio:_w},ri=gs(qc);function Th(t,e,r){if(e.length>255)throw new Error("Context is too big");return as(Rc("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var YI=gs({...qc,domain:Th}),WI=gs({...qc,domain:Th,prehash:Pc});var Aw=(xr.ORDER+BigInt(3))/BigInt(8),QI=xr.pow(Kc,Aw),XI=xr.sqrt(xr.neg(xr.ONE)),ZI=(xr.ORDER-BigInt(5))/BigInt(8),jI=BigInt(486662);var JI=Ah(xr,xr.neg(BigInt(486664)));var eR=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tR=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),rR=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),nR=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var iR=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ni=32,br=64,xs=32;async function Bh(){let t=ri.utils.randomPrivateKey(),e=ri.getPublicKey(t);return{privateKey:Nh(t,e),publicKey:e}}async function Lh(t){if(t.length!==xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=ri.getPublicKey(e);return{privateKey:Nh(e,r),publicKey:r}}async function Ph(t,e){let r=t.subarray(0,xs);return ri.sign(e,r)}async function Dh(t,e,r){return ri.verify(e,r,t)}function Nh(t,e){let r=new Uint8Array(br);for(let n=0;n<xs;n++)r[n]=t[n],r[xs+n]=e[n];return r}function Me(t,e){e==null&&(e=t.reduce((i,o)=>i+o.length,0));let r=Dt(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return cn(r)}var dt={get(t=globalThis){let e=t.crypto;if(e==null||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-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Vc={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function bs(t){let e=t?.algorithm??"AES-GCM",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"SHA-256",o=t?.saltLength??16,s=t?.iterations??32767,a=dt.get();r*=8;async function c(f,h){let p=a.getRandomValues(new Uint8Array(o)),d=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:d};typeof h=="string"&&(h=Y(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},w=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,w,{name:e,length:r},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},w=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,w,{name:e,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(m,y,f);return Me([p,m.iv,new Uint8Array(g)])}async function u(f,h){let p=f.subarray(0,o),d=f.subarray(o,o+n),m=f.subarray(o+n),y={name:e,iv:d};typeof h=="string"&&(h=Y(h));let g;if(h.length===0)try{let w={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},C=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,C,{name:e,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Vc,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:p,iterations:s,hash:{name:i}},C=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(w,C,{name:e,length:r},!0,["decrypt"])}let x=await a.subtle.decrypt(y,g,m);return new Uint8Array(x)}return{encrypt:c,decrypt:u}}async function ii(t,e){let n=await bs().encrypt(t,e);return un.encode(n)}var tu=J(Yc(),1),vd=J(pd(),1),_d=J(yn(),1),ru=J(eu(),1),Ad=J(Ed(),1);function Nw(){_d.default._configure(),tu.default._configure(vd.default),ru.default._configure(Ad.default)}Nw();var Sd=["uint64","int64","sint64","fixed64","sfixed64"];function kw(t){for(let e of Sd){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function nu(t){return kw(new tu.default(t))}function Ow(t){for(let e of Sd){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function iu(){return Ow(ru.default.create())}function tt(t,e){let r=nu(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function rt(t,e){let r=iu();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var si;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(si||(si={}));function As(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function ou(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return As("enum",si.VARINT,r,n)}function nt(t,e){return As("message",si.LENGTH_DELIMITED,t,e)}var Te;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(Te||(Te={}));var su;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})(su||(su={}));(function(t){t.codec=()=>ou(su)})(Te||(Te={}));var ir;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Te.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=Te.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(ir||(ir={}));var or;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Te.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=Te.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(or||(or={}));var Ji=class{_key;constructor(e){this._key=ai(e,ni)}async verify(e,r){return Dh(this._key,r,e)}marshal(){return this._key}get bytes(){return ir.encode({Type:Te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},xn=class{_key;_publicKey;constructor(e,r){this._key=ai(e,br),this._publicKey=ai(r,ni)}async sign(e){return Ph(this._key,e)}get public(){return new Ji(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:Te.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=Nr.digest(this.public.bytes);return Oe.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Mw(t){if(t.length>br){t=ai(t,br+ni);let n=t.subarray(0,br),i=t.subarray(br,t.length);return new xn(n,i)}t=ai(t,br);let e=t.subarray(0,br),r=t.subarray(ni);return new xn(e,r)}function Uw(t){return t=ai(t,ni),new Ji(t)}async function Kw(){let{privateKey:t,publicKey:e}=await Bh();return new xn(t,e)}async function Id(t){let{privateKey:e,publicKey:r}=await Lh(t);return new xn(e,r)}function ai(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}function ee(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var JR=J(ke(),1),e4=J(Jo(),1),Rd=J(ye(),1);function Ft(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Me([new Uint8Array(e-r.length),r])}return ee(r,"base64url")}function gt(t){let e=Cd(t);return new Rd.default.jsbn.BigInteger(ee(e,"base16"),16)}function Cd(t,e){let r=Y(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Me([new Uint8Array(e-r.length),r])}return r}var Fw={"P-256":256,"P-384":384,"P-521":521},qw=Object.keys(Fw),f4=qw.join(" / ");async function Td(t,e){let r=un.decode(t);return bs().decrypt(r,e)}var hu={};He(hu,{MAX_KEY_SIZE:()=>no,RsaPrivateKey:()=>ci,RsaPublicKey:()=>ro,fromJwk:()=>Zw,generateKeyPair:()=>jw,unmarshalRsaPrivateKey:()=>Qw,unmarshalRsaPublicKey:()=>Xw});var to=J(ye(),1);var Q4=J(kd(),1);function wn(t){if(isNaN(t)||t<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return hn(t)}var L4=J(rs(),1),lu=J(ye(),1);function Od(t,e){return e.map(r=>gt(t[r]))}function Md(t){return lu.default.pki.setRsaPrivateKey(...Od(t,["n","e","d","p","q","dp","dq","qi"]))}function Ud(t){return lu.default.pki.setRsaPublicKey(...Od(t,["n","e"]))}var En={};He(En,{jwkToPkcs1:()=>zw,jwkToPkix:()=>Gw,pkcs1ToJwk:()=>$w,pkixToJwk:()=>Hw});var N4=J(qi(),1),k4=J(rs(),1);var wr=J(ye(),1);function $w(t){let e=wr.default.asn1.fromDer(ee(t,"ascii")),r=wr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Ft(r.n),e:Ft(r.e),d:Ft(r.d),p:Ft(r.p),q:Ft(r.q),dp:Ft(r.dP),dq:Ft(r.dQ),qi:Ft(r.qInv),alg:"RS256"}}function zw(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=wr.default.pki.privateKeyToAsn1({n:gt(t.n),e:gt(t.e),d:gt(t.d),p:gt(t.p),q:gt(t.q),dP:gt(t.dp),dQ:gt(t.dq),qInv:gt(t.qi)});return Y(wr.default.asn1.toDer(e).getBytes(),"ascii")}function Hw(t){let e=wr.default.asn1.fromDer(ee(t,"ascii")),r=wr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Ft(r.n),e:Ft(r.e)}}function Gw(t){if(t.n==null||t.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let e=wr.default.pki.publicKeyToAsn1({n:gt(t.n),e:gt(t.e)});return Y(wr.default.asn1.toDer(e).getBytes(),"ascii")}async function Kd(t){let e=await dt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Vd(e);return{privateKey:r[0],publicKey:r[1]}}async function fu(t){let r=[await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Yw(t)],n=await Vd({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function Fd(t,e){let r=await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await dt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function qd(t,e,r){let n=await dt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return dt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)}async function Vd(t){if(t.privateKey==null||t.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([dt.get().subtle.exportKey("jwk",t.privateKey),dt.get().subtle.exportKey("jwk",t.publicKey)])}async function Yw(t){return dt.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function $d(t,e,r,n){let i=e?Ud(t):Md(t),o=ee(Uint8Array.from(r),"ascii"),s=n(o,i);return Y(s,"ascii")}function zd(t,e){return $d(t,!0,e,(r,n)=>n.encrypt(r))}function Hd(t,e){return $d(t,!1,e,(r,n)=>n.decrypt(r))}function Is(t){if(t.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(t.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Y(t.n,"base64url").length*8}var no=8192,ro=class{_key;constructor(e){this._key=e}async verify(e,r){return qd(this._key,r,e)}marshal(){return En.jwkToPkix(this._key)}get bytes(){return ir.encode({Type:Te.RSA,Data:this.marshal()}).subarray()}encrypt(e){return zd(this._key,e)}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},ci=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return wn(16)}async sign(e){return Fd(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new ro(this._publicKey)}decrypt(e){return Hd(this._key,e)}marshal(){return En.jwkToPkcs1(this._key)}get bytes(){return or.encode({Type:Te.RSA,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return ee(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new to.default.util.ByteBuffer(this.marshal()),i=to.default.asn1.fromDer(n),o=to.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return to.default.pki.encryptRsaPrivateKey(o,e,s)}else{if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function Qw(t){let e=En.pkcs1ToJwk(t);if(Is(e)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await fu(e);return new ci(r.privateKey,r.publicKey)}function Xw(t){let e=En.pkixToJwk(t);if(Is(e)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new ro(e)}async function Zw(t){if(Is(t)>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await fu(t);return new ci(e.privateKey,e.publicKey)}async function jw(t){if(t>no)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Kd(t);return new ci(e.privateKey,e.publicKey)}var xu={};He(xu,{Secp256k1PrivateKey:()=>oo,Secp256k1PublicKey:()=>io,generateKeyPair:()=>dE,unmarshalSecp256k1PrivateKey:()=>fE,unmarshalSecp256k1PublicKey:()=>hE});var Jw=(t,e,r)=>t&e^~t&r,eE=(t,e,r)=>t&e^t&r^e&r,tE=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]),Vr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$r=new Uint32Array(64),Rs=class extends ei{constructor(){super(64,32,8,!1),this.A=Vr[0]|0,this.B=Vr[1]|0,this.C=Vr[2]|0,this.D=Vr[3]|0,this.E=Vr[4]|0,this.F=Vr[5]|0,this.G=Vr[6]|0,this.H=Vr[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,r,n,i,o,s,a,c]}set(e,r,n,i,o,s,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)$r[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=$r[f-15],p=$r[f-2],d=Nt(h,7)^Nt(h,18)^h>>>3,m=Nt(p,17)^Nt(p,19)^p>>>10;$r[f]=m+$r[f-7]+d+$r[f-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let h=Nt(a,6)^Nt(a,11)^Nt(a,25),p=l+h+Jw(a,c,u)+tE[f]+$r[f]|0,m=(Nt(n,2)^Nt(n,13)^Nt(n,22))+eE(n,i,o)|0;l=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+m|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,o,s,a,c,u,l)}roundClean(){$r.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},du=class extends Rs{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}},Gd=Or(()=>new Rs),e8=Or(()=>new du);function rE(t){let e=Xi(t);It(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:nE,hexToBytes:iE}=fs,vn={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=vn;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:nE(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=vn,r=typeof t=="string"?iE(t):t;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=vn._parseInt(r.subarray(2)),{d:s,l:a}=vn._parseInt(o);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,a=r(o),c=r(s);return`30${r(s+o+4)}02${c}${i}02${a}${n}`}},Er=BigInt(0),Ct=BigInt(1),o8=BigInt(2),Yd=BigInt(3),s8=BigInt(4);function oE(t){let e=rE(t),{Fp:r}=e,n=e.toBytes||((d,m,y)=>{let g=m.toAffine();return Ot(Uint8Array.from([4]),r.toBytes(g.x),r.toBytes(g.y))}),i=e.fromBytes||(d=>{let m=d.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),g=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:g}});function o(d){let{a:m,b:y}=e,g=r.sqr(d),x=r.mul(g,d);return r.add(r.add(x,r.mul(d,m)),y)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(d){return typeof d=="bigint"&&Er<d&&d<e.n}function a(d){if(!s(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:g,n:x}=e;if(m&&typeof d!="bigint"){if(d instanceof Uint8Array&&(d=er(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(y*2,"0")}let w;try{w=typeof d=="bigint"?d:kt(ve("private key",d,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof d}`)}return g&&(w=de(w,x)),a(w),w}let u=new Map;function l(d){if(!(d instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(m,y,g){if(this.px=m,this.py=y,this.pz=g,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(g==null||!r.isValid(g))throw new Error("z required")}static fromAffine(m){let{x:y,y:g}=m||{};if(!m||!r.isValid(y)||!r.isValid(g))throw new Error("invalid affine point");if(m instanceof f)throw new Error("projective point not allowed");let x=w=>r.eql(w,r.ZERO);return x(y)&&x(g)?f.ZERO:new f(y,g,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(g=>g.pz));return m.map((g,x)=>g.toAffine(y[x])).map(f.fromAffine)}static fromHex(m){let y=f.fromAffine(i(ve("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint)return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let g=r.sqr(y),x=o(m);if(!r.eql(g,x))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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){l(m);let{px:y,py:g,pz:x}=this,{px:w,py:C,pz:_}=m,A=r.eql(r.mul(y,_),r.mul(w,x)),P=r.eql(r.mul(g,_),r.mul(C,x));return A&&P}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,g=r.mul(y,Yd),{px:x,py:w,pz:C}=this,_=r.ZERO,A=r.ZERO,P=r.ZERO,D=r.mul(x,x),W=r.mul(w,w),Q=r.mul(C,C),H=r.mul(x,w);return H=r.add(H,H),P=r.mul(x,C),P=r.add(P,P),_=r.mul(m,P),A=r.mul(g,Q),A=r.add(_,A),_=r.sub(W,A),A=r.add(W,A),A=r.mul(_,A),_=r.mul(H,_),P=r.mul(g,P),Q=r.mul(m,Q),H=r.sub(D,Q),H=r.mul(m,H),H=r.add(H,P),P=r.add(D,D),D=r.add(P,D),D=r.add(D,Q),D=r.mul(D,H),A=r.add(A,D),Q=r.mul(w,C),Q=r.add(Q,Q),D=r.mul(Q,H),_=r.sub(_,D),P=r.mul(Q,W),P=r.add(P,P),P=r.add(P,P),new f(_,A,P)}add(m){l(m);let{px:y,py:g,pz:x}=this,{px:w,py:C,pz:_}=m,A=r.ZERO,P=r.ZERO,D=r.ZERO,W=e.a,Q=r.mul(e.b,Yd),H=r.mul(y,w),ne=r.mul(g,C),ge=r.mul(x,_),Ze=r.add(y,g),T=r.add(w,C);Ze=r.mul(Ze,T),T=r.add(H,ne),Ze=r.sub(Ze,T),T=r.add(y,x);let k=r.add(w,_);return T=r.mul(T,k),k=r.add(H,ge),T=r.sub(T,k),k=r.add(g,x),A=r.add(C,_),k=r.mul(k,A),A=r.add(ne,ge),k=r.sub(k,A),D=r.mul(W,T),A=r.mul(Q,ge),D=r.add(A,D),A=r.sub(ne,D),D=r.add(ne,D),P=r.mul(A,D),ne=r.add(H,H),ne=r.add(ne,H),ge=r.mul(W,ge),T=r.mul(Q,T),ne=r.add(ne,ge),ge=r.sub(H,ge),ge=r.mul(W,ge),T=r.add(T,ge),H=r.mul(ne,T),P=r.add(P,H),H=r.mul(k,T),A=r.mul(Ze,A),A=r.sub(A,H),H=r.mul(Ze,ne),D=r.mul(k,D),D=r.add(D,H),new f(A,P,D)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return p.wNAFCached(this,u,m,y=>{let g=r.invertBatch(y.map(x=>x.pz));return y.map((x,w)=>x.toAffine(g[w])).map(f.fromAffine)})}multiplyUnsafe(m){let y=f.ZERO;if(m===Er)return y;if(a(m),m===Ct)return this;let{endo:g}=e;if(!g)return p.unsafeLadder(this,m);let{k1neg:x,k1:w,k2neg:C,k2:_}=g.splitScalar(m),A=y,P=y,D=this;for(;w>Er||_>Er;)w&Ct&&(A=A.add(D)),_&Ct&&(P=P.add(D)),D=D.double(),w>>=Ct,_>>=Ct;return x&&(A=A.negate()),C&&(P=P.negate()),P=new f(r.mul(P.px,g.beta),P.py,P.pz),A.add(P)}multiply(m){a(m);let y=m,g,x,{endo:w}=e;if(w){let{k1neg:C,k1:_,k2neg:A,k2:P}=w.splitScalar(y),{p:D,f:W}=this.wNAF(_),{p:Q,f:H}=this.wNAF(P);D=p.constTimeNegate(C,D),Q=p.constTimeNegate(A,Q),Q=new f(r.mul(Q.px,w.beta),Q.py,Q.pz),g=D.add(Q),x=W.add(H)}else{let{p:C,f:_}=this.wNAF(y);g=C,x=_}return f.normalizeZ([g,x])[0]}multiplyAndAddUnsafe(m,y,g){let x=f.BASE,w=(_,A)=>A===Er||A===Ct||!_.equals(x)?_.multiplyUnsafe(A):_.multiply(A),C=w(this,y).add(w(m,g));return C.is0()?void 0:C}toAffine(m){let{px:y,py:g,pz:x}=this,w=this.is0();m==null&&(m=w?r.ONE:r.inv(x));let C=r.mul(y,m),_=r.mul(g,m),A=r.mul(x,m);if(w)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:C,y:_}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Ct)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===Ct?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(f,this,m)}toHex(m=!0){return er(this.toRawBytes(m))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=ms(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function sE(t){let e=Xi(t);return It(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Wd(t){let e=sE(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(T){return Er<T&&T<r.ORDER}function a(T){return de(T,n)}function c(T){return hs(T,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:f,isWithinCurveOrder:h}=oE({...e,toBytes(T,k,L){let N=k.toAffine(),I=r.toBytes(N.x),K=Ot;return L?K(Uint8Array.from([k.hasEvenY()?2:3]),I):K(Uint8Array.from([4]),I,r.toBytes(N.y))},fromBytes(T){let k=T.length,L=T[0],N=T.subarray(1);if(k===i&&(L===2||L===3)){let I=kt(N);if(!s(I))throw new Error("Point is not on curve");let K=f(I),V=r.sqrt(K),G=(V&Ct)===Ct;return(L&1)===1!==G&&(V=r.neg(V)),{x:I,y:V}}else if(k===o&&L===4){let I=r.fromBytes(N.subarray(0,r.BYTES)),K=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:I,y:K}}else throw new Error(`Point of length ${k} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=T=>er(gr(T,e.nByteLength));function d(T){let k=n>>Ct;return T>k}function m(T){return d(T)?a(-T):T}let y=(T,k,L)=>kt(T.slice(k,L));class g{constructor(k,L,N){this.r=k,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(k){let L=e.nByteLength;return k=ve("compactSignature",k,L*2),new g(y(k,0,L),y(k,L,2*L))}static fromDER(k){let{r:L,s:N}=vn.toSig(ve("DER",k));return new g(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(k){return new g(this.r,this.s,k)}recoverPublicKey(k){let{r:L,s:N,recovery:I}=this,K=P(ve("msgHash",k));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let V=I===2||I===3?L+e.n:L;if(V>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let G=I&1?"03":"02",te=u.fromHex(G+p(V)),oe=c(V),me=a(-K*oe),se=a(N*oe),fe=u.BASE.multiplyAndAddUnsafe(te,me,se);if(!fe)throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return dn(this.toDERHex())}toDERHex(){return vn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dn(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let x={isValidPrivateKey(T){try{return l(T),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let T=e.randomBytes(r.BYTES+8),k=Sh(T,n);return gr(k,e.nByteLength)},precompute(T=8,k=u.BASE){return k._setWindowSize(T),k.multiply(BigInt(3)),k}};function w(T,k=!0){return u.fromPrivateKey(T).toRawBytes(k)}function C(T){let k=T instanceof Uint8Array,L=typeof T=="string",N=(k||L)&&T.length;return k?N===i||N===o:L?N===2*i||N===2*o:T instanceof u}function _(T,k,L=!0){if(C(T))throw new Error("first arg must be private key");if(!C(k))throw new Error("second arg must be public key");return u.fromHex(k).multiply(l(T)).toRawBytes(L)}let A=e.bits2int||function(T){let k=kt(T),L=T.length*8-e.nBitLength;return L>0?k>>BigInt(L):k},P=e.bits2int_modN||function(T){return a(A(T))},D=Qi(e.nBitLength);function W(T){if(typeof T!="bigint")throw new Error("bigint expected");if(!(Er<=T&&T<D))throw new Error(`bigint expected < 2^${e.nBitLength}`);return gr(T,e.nByteLength)}function Q(T,k,L=H){if(["recovered","canonical"].some(De=>De in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:I}=e,{lowS:K,prehash:V,extraEntropy:G}=L;K==null&&(K=!0),T=ve("msgHash",T),V&&(T=ve("prehashed msgHash",N(T)));let te=P(T),oe=l(k),me=[W(oe),W(te)];if(G!=null){let De=G===!0?I(r.BYTES):G;me.push(ve("extraEntropy",De,r.BYTES))}let se=Ot(...me),fe=te;function Fe(De){let je=A(De);if(!h(je))return;let Je=c(je),Ve=u.BASE.multiply(je).toAffine(),st=a(Ve.x);if(st===Er)return;let lr=a(Je*a(fe+st*oe));if(lr===Er)return;let tn=(Ve.x===st?0:2)|Number(Ve.y&Ct),Mi=lr;return K&&d(lr)&&(Mi=m(lr),tn^=1),new g(st,Mi,tn)}return{seed:se,k2sig:Fe}}let H={lowS:e.lowS,prehash:!1},ne={lowS:e.lowS,prehash:!1};function ge(T,k,L=H){let{seed:N,k2sig:I}=Q(T,k,L),K=e;return kc(K.hash.outputLen,K.nByteLength,K.hmac)(N,I)}u.BASE._setWindowSize(8);function Ze(T,k,L,N=ne){let I=T;if(k=ve("msgHash",k),L=ve("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:K,prehash:V}=N,G,te;try{if(typeof I=="string"||I instanceof Uint8Array)try{G=g.fromDER(I)}catch(Ve){if(!(Ve instanceof vn.Err))throw Ve;G=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:Ve,s:st}=I;G=new g(Ve,st)}else throw new Error("PARSE");te=u.fromHex(L)}catch(Ve){if(Ve.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(K&&G.hasHighS())return!1;V&&(k=e.hash(k));let{r:oe,s:me}=G,se=P(k),fe=c(me),Fe=a(se*fe),De=a(oe*fe),je=u.BASE.multiplyAndAddUnsafe(te,Fe,De)?.toAffine();return je?a(je.x)===oe:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:_,sign:ge,verify:Ze,ProjectivePoint:u,Signature:g,utils:x}}var Cs=class extends Jn{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,yr.hash(e);let n=Wi(r);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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(e){return yr.exists(this),this.iHash.update(e),this}digestInto(e){yr.exists(this),yr.bytes(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},pu=(t,e,r)=>new Cs(t,e).update(r).digest();pu.create=(t,e)=>new Cs(t,e);function aE(t){return{hash:t,hmac:(e,...r)=>pu(t,e,as(...r)),randomBytes:hn}}function Qd(t,e){let r=n=>Wd({...t,...aE(n)});return Object.freeze({...r(e),create:r})}var jd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cE=BigInt(1),mu=BigInt(2),Zd=(t,e)=>(t+e/mu)/e;function uE(t){let e=jd,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Ce(l,r,e)*l%e,h=Ce(f,r,e)*l%e,p=Ce(h,mu,e)*u%e,d=Ce(p,i,e)*p%e,m=Ce(d,o,e)*d%e,y=Ce(m,a,e)*m%e,g=Ce(y,c,e)*y%e,x=Ce(g,a,e)*m%e,w=Ce(x,r,e)*l%e,C=Ce(w,s,e)*d%e,_=Ce(C,n,e)*u%e,A=Ce(_,mu,e);if(!yu.eql(yu.sqr(A),t))throw new Error("Cannot find square root");return A}var yu=ps(jd,void 0,void 0,{sqrt:uE}),vr=Qd({a:BigInt(0),b:BigInt(7),Fp:yu,n:Xd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=Xd,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=Zd(o*t,e),c=Zd(-n*t,e),u=de(t-a*r-c*i,e),l=de(-a*n-c*o,e),f=u>s,h=l>s;if(f&&(u=e-u),h&&(l=e-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}}},Gd),A8=BigInt(0);var S8=vr.ProjectivePoint;function Jd(){return vr.utils.randomPrivateKey()}async function ep(t,e){let{digest:r}=await et.digest(e);try{return vr.sign(r,t).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}async function tp(t,e,r){try{let{digest:n}=await et.digest(r);return vr.verify(e,n,t)}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function rp(t){return vr.ProjectivePoint.fromHex(t).toRawBytes(!0)}function np(t){try{vr.getPublicKey(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function gu(t){try{vr.ProjectivePoint.fromHex(t)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function ip(t){try{return vr.getPublicKey(t,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var io=class{_key;constructor(e){gu(e),this._key=e}async verify(e,r){return tp(this._key,r,e)}marshal(){return rp(this._key)}get bytes(){return ir.encode({Type:Te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},oo=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??ip(e),np(this._key),gu(this._publicKey)}async sign(e){return ep(this._key,e)}get public(){return new io(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:Te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Le(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return ee(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return ii(this.bytes,e);throw new E(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function fE(t){return new oo(t)}function hE(t){return new io(t)}async function dE(){let t=Jd();return new oo(t)}var _r={rsa:hu,ed25519:au,secp256k1:xu};function bu(t){let e=Object.keys(_r).join(" / ");return new E(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function wu(t){if(t=t.toLowerCase(),t==="rsa"||t==="ed25519"||t==="secp256k1")return _r[t];throw bu(t)}async function Bs(t,e){return wu(t).generateKeyPair(e??2048)}function so(t){let e=ir.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Te.RSA:return _r.rsa.unmarshalRsaPublicKey(r);case Te.Ed25519:return _r.ed25519.unmarshalEd25519PublicKey(r);case Te.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw bu(e.Type??"RSA")}}function op(t,e){return e=(e??"rsa").toLowerCase(),wu(e),t.bytes}async function ui(t){let e=or.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Te.RSA:return _r.rsa.unmarshalRsaPrivateKey(r);case Te.Ed25519:return _r.ed25519.unmarshalEd25519PrivateKey(r);case Te.Secp256k1:return _r.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw bu(e.Type??"RSA")}}function sp(t,e){return e=(e??"rsa").toLowerCase(),wu(e),t.bytes}async function ao(t,e){try{let i=await Td(t,e);return await ui(i)}catch{}let r=Ts.default.pki.decryptRsaPrivateKey(t,e);if(r===null)throw new E("Cannot read the key, most likely the password is wrong or not a RSA key","ERR_CANNOT_DECRYPT_PEM");let n=Ts.default.asn1.toDer(Ts.default.pki.privateKeyToAsn1(r));return n=Y(n.getBytes(),"ascii"),_r.rsa.unmarshalRsaPrivateKey(n)}var Eu=Symbol.for("@libp2p/content-routing");var co=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new _u(e,r))}},vu=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},_u=globalThis.CustomEvent??vu;var Au=Symbol.for("@libp2p/peer-discovery");var Su=Symbol.for("@libp2p/peer-routing");var X8=J(Ho(),1),mE=J(ye(),1);var cp=J(Qa(),1),up=J(ke(),1),ap={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function uo(t,e,r,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(ap).join(" / ");throw new E(`Hash '${i}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let o=ap[i],s=(0,cp.default)(t,e,r,n,o);return up.default.encode64(s,null)}var bt=J(Ru(),1);bt.default.formatters.b=t=>t==null?"undefined":Oe.baseEncode(t);bt.default.formatters.t=t=>t==null?"undefined":mt.baseEncode(t);bt.default.formatters.m=t=>t==null?"undefined":un.baseEncode(t);bt.default.formatters.p=t=>t==null?"undefined":t.toString();bt.default.formatters.c=t=>t==null?"undefined":t.toString();bt.default.formatters.k=t=>t==null?"undefined":t.toString();bt.default.formatters.a=t=>t==null?"undefined":t.toString();function BE(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function ie(t){let e=BE(`${t}:trace`);return bt.default.enabled(`${t}:trace`)&&bt.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,bt.default)(`${t}:trace`)),Object.assign((0,bt.default)(t),{error:(0,bt.default)(`${t}:error`),trace:e})}var Cu=Symbol.for("@libp2p/peer-id");function Ds(t){return t!=null&&!!t[Cu]}var LE=Symbol.for("nodejs.util.inspect.custom"),dp=Object.values(kr).map(t=>t.decoder).reduce((t,e)=>t.or(e),kr.identity.decoder),pp=114,Tu=36,Bu=37,lo=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Cu]=!0;toString(){return this.string==null&&(this.string=Oe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Pt.createV1(pp,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return Le(this.multihash.bytes,e);if(typeof e=="string")return pe(e).equals(this);if(e?.multihash?.bytes!=null)return Le(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[LE](){return`PeerId(${this.toString()})`}},An=class extends lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sn=class extends lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},In=class extends lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function mp(t){if(t.type==="RSA")return new An(t);if(t.type==="Ed25519")return new Sn(t);if(t.type==="secp256k1")return new In(t);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function pe(t,e){if(e=e??dp,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=ln(Oe.decode(`z${t}`));return t.startsWith("12D")?new Sn({multihash:r}):t.startsWith("16U")?new In({multihash:r}):new An({multihash:r})}return di(dp.decode(t))}function di(t){try{let e=ln(t);if(e.code===Nr.code){if(e.digest.length===Tu)return new Sn({multihash:e});if(e.digest.length===Bu)return new In({multihash:e})}if(e.code===et.code)return new An({multihash:e})}catch{return PE(Pt.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function PE(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==pp)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===et.code)return new An({multihash:t.multihash});if(e.code===Nr.code){if(e.digest.length===Tu)return new Sn({multihash:t.multihash});if(e.digest.length===Bu)return new In({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function pi(t,e){return t.length===Tu?new Sn({multihash:Jt(Nr.code,t),privateKey:e}):t.length===Bu?new In({multihash:Jt(Nr.code,t),privateKey:e}):new An({multihash:await et.digest(t),publicKey:t,privateKey:e})}var Ns=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var Ar="/",yp=new TextEncoder().encode(Ar),ks=yp[0],sr=class t{_buf;constructor(e,r){if(typeof e=="string")this._buf=Y(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(r==null&&(r=!0),r&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ks)throw new Error("Invalid key")}toString(e="utf8"){return ee(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new t(e.join(Ar))}static random(){return new t(Ns().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new t(e):typeof e.uint8Array=="function"?new t(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=yp),this._buf[0]!==ks){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ks,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ks;)this._buf=this._buf.subarray(0,-1)}less(e){let r=this.list(),n=e.list();for(let i=0;i<r.length;i++){if(n.length<i+1)return!1;let o=r[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return r.length<n.length}reverse(){return t.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ar).slice(1)}type(){return DE(this.baseNamespace())}name(){return NE(this.baseNamespace())}instance(e){return new t(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ar)||(e+=Ar),e+=this.type(),new t(e)}parent(){let e=this.list();return e.length===1?new t(Ar):new t(e.slice(0,-1).join(Ar))}child(e){return this.toString()===Ar?e:e.toString()===Ar?this:new t(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 t.withNamespaces([...this.namespaces(),...kE(e.map(r=>r.namespaces()))])}};function DE(t){let e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function NE(t){let e=t.split(":");return e[e.length-1]}function kE(t){return[].concat(...t)}var Sp=J(Ap(),1),zr=Sp.default;var kp=J(Np(),1);var ce;(function(t){t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(ce||(ce={}));var Us=ie("libp2p:keychain"),JE="/pkcs8/",Op="/info/",Rn=new WeakMap,Cn={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},Pu={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Sr(t){return t==null||typeof t!="string"?!1:t===(0,kp.default)(t.trim())&&t.length>0}async function be(){let r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function ar(t){return new sr(JE+t)}function Hr(t){return new sr(Op+t)}var Tn=class{components;init;constructor(e,r){if(this.components=e,this.init=zr(Pu,r),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<Cn.minKeyLength)throw new Error(`dek.keyLength must be least ${Cn.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<Cn.minSaltLength)throw new Error(`dek.saltLength must be least ${Cn.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<Cn.minIterationCount)throw new Error(`dek.iterationCount must be least ${Cn.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?uo(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Rn.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},Pu),r=Math.ceil(Cn.minSaltLength/3)*3;return e.dek.salt=ee(wn(r),"base64"),e}static get options(){return Pu}async createKey(e,r,n=2048){if(!Sr(e)||e==="self")throw await be(),new E("Invalid key name",ce.ERR_INVALID_KEY_NAME);if(typeof r!="string")throw await be(),new E("Invalid key type",ce.ERR_INVALID_KEY_TYPE);let i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E("Key name already exists",ce.ERR_KEY_ALREADY_EXISTS);switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await be(),new E("Invalid RSA key size",ce.ERR_INVALID_KEY_SIZE);break;default:break}let s;try{let a=await Bs(r,n),c=await a.id(),u=Rn.get(this);if(u==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let l=u.dek,f=await a.export(l);s={name:e,id:c};let h=this.components.datastore.batch();h.put(i,Y(f)),h.put(Hr(e),Y(JSON.stringify(s))),await h.commit()}catch(a){throw await be(),a}return s}async listKeys(){let e={prefix:Op},r=[];for await(let n of this.components.datastore.query(e))r.push(JSON.parse(ee(n.value)));return r}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new E(`Key with id '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND);return n}catch(r){throw await be(),r}}async findKeyByName(e){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);let r=Hr(e);try{let n=await this.components.datastore.get(r);return JSON.parse(ee(n))}catch(n){throw await be(),Us.error(n),new E(`Key '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);let r=ar(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(r),i.delete(Hr(e)),await i.commit(),n}async renameKey(e,r){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid old key name '${e}'`,ce.ERR_OLD_KEY_NAME_INVALID);if(!Sr(r)||r==="self")throw await be(),new E(`Invalid new key name '${r}'`,ce.ERR_NEW_KEY_NAME_INVALID);let n=ar(e),i=ar(r),o=Hr(e),s=Hr(r);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${r}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(o),l=JSON.parse(ee(u));l.name=r;let f=this.components.datastore.batch();return f.put(i,c),f.put(s,Y(JSON.stringify(l))),f.delete(n),f.delete(o),await f.commit(),l}catch(c){throw await be(),c}}async exportKey(e,r){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),new E("Password is required",ce.ERR_PASSWORD_REQUIRED);let n=ar(e);try{let i=await this.components.datastore.get(n),o=ee(i),s=Rn.get(this);if(s==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let a=s.dek;return await(await ao(o,a)).export(r)}catch(i){throw await be(),i}}async exportPeerId(e){let r="temporary-password",n=await this.exportKey(e,r),i=await ao(n,r);return pi(i.public.bytes,i.bytes)}async importKey(e,r,n){if(!Sr(e)||e==="self")throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),new E("PEM encoded key is required",ce.ERR_PEM_REQUIRED);let i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${e}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);let s;try{s=await ao(r,n)}catch{throw await be(),new E("Cannot read the key, most likely the password is wrong",ce.ERR_CANNOT_READ_KEY)}let a;try{a=await s.id();let l=Rn.get(this);if(l==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let f=l.dek;r=await s.export(f)}catch(l){throw await be(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,Y(r)),u.put(Hr(e),Y(JSON.stringify(c))),await u.commit(),c}async importPeer(e,r){try{if(!Sr(e))throw new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);if(r==null)throw new E("PeerId is required",ce.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw new E("PeerId.privKey is required",ce.ERR_MISSING_PRIVATE_KEY);let n=await ui(r.privateKey),i=ar(e);if(await this.components.datastore.has(i))throw await be(),new E(`Key '${e}' already exists`,ce.ERR_KEY_ALREADY_EXISTS);let s=Rn.get(this);if(s==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let a=s.dek,c=await n.export(a),u={name:e,id:r.toString()},l=this.components.datastore.batch();return l.put(i,Y(c)),l.put(Hr(e),Y(JSON.stringify(u))),await l.commit(),u}catch(n){throw await be(),n}}async getPrivateKey(e){if(!Sr(e))throw await be(),new E(`Invalid key name '${e}'`,ce.ERR_INVALID_KEY_NAME);try{let r=ar(e),n=await this.components.datastore.get(r);return ee(n)}catch(r){throw await be(),Us.error(r),new E(`Key '${e}' does not exist.`,ce.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,r){if(typeof e!="string")throw await be(),new E(`Invalid old pass type '${typeof e}'`,ce.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await be(),new E(`Invalid new pass type '${typeof r}'`,ce.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await be(),new E(`Invalid pass length ${r.length}`,ce.ERR_INVALID_PASS_LENGTH);Us("recreating keychain");let n=Rn.get(this);if(n==null)throw new E("dek missing",ce.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=r;let o=r!=null&&this.init.dek?.salt!=null?uo(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Rn.set(this,{dek:o});let s=await this.listKeys();for(let a of s){let c=await this.components.datastore.get(ar(a.name)),u=ee(c),l=await ao(u,i),f=o.toString(),h=await l.export(f),p=this.components.datastore.batch(),d={name:a.name,id:a.id};p.put(ar(a.name),Y(h)),p.put(Hr(a.name),Y(JSON.stringify(d))),await p.commit()}Us("keychain reconstructed")}};function Ir(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return r}var qt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return Ir(this.map.entries(),e=>[pe(e[0]),e[1]])}forEach(e){this.map.forEach((r,n)=>{e(r,pe(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),r)}keys(){return Ir(this.map.keys(),e=>pe(e))}values(){return this.map.values()}get size(){return this.map.size}};var Bn=class t{set;constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.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 Ir(this.set.entries(),e=>{let r=pe(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=pe(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ir(this.set.values(),e=>pe(e))}intersection(e){let r=new t;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new t;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new t;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var Du=class t{list;constructor(e){if(this.list=[],e!=null)for(let r of e)this.list.push(r.toString())}[Symbol.iterator](){return Ir(this.list.entries(),e=>pe(e[1]))}concat(e){let r=new t(this);for(let n of e)r.push(n);return r}entries(){return Ir(this.list.entries(),e=>[e[0],pe(e[1])])}every(e){return this.list.every((r,n)=>e(pe(r),n,this))}filter(e){let r=new t;return this.list.forEach((n,i)=>{let o=pe(n);e(o,i,this)&&r.push(o)}),r}find(e){let r=this.list.find((n,i)=>e(pe(n),i,this));if(r!=null)return pe(r)}findIndex(e){return this.list.findIndex((r,n)=>e(pe(r),n,this))}forEach(e){this.list.forEach((r,n)=>{e(pe(r),n,this)})}includes(e){return this.list.includes(e.toString())}indexOf(e){return this.list.indexOf(e.toString())}pop(){let e=this.list.pop();if(e!=null)return pe(e)}push(...e){for(let r of e)this.list.push(r.toString())}shift(){let e=this.list.shift();if(e!=null)return pe(e)}unshift(...e){let r=this.list.length;for(let n=e.length-1;n>-1;n--)r=this.list.unshift(e[n].toString());return r}get length(){return this.list.length}};var Nu;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.id!=null&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(Nu||(Nu={}));var Mp=async()=>{let t=await Bs("Ed25519"),e=await ev(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function ev(t){return pi(op(t.public),sp(t))}function Ks(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var Up=4294967296,fo=class t{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new t(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new t(r,n)}toBytes(e,r=0){let n=Ks(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new t;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>Up&&(i=0,++n>Up&&(n=0))),new t(n,i)}static fromNumber(e){if(e===0)return new t;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(i,n)}static fromBytes(e,r=0){let n=Ks(e),i=new t,o=0;if(e.length-r>4){for(;o<4;++o)if(i.lo=(i.lo|(n.get(r)&127)<<o*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;o=0}else for(;o<4;++o){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<o*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;o<5;++o)if(i.hi=(i.hi|(n.get(r)&127)<<o*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;o<5;++o){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<o*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var tv=Math.pow(2,7),rv=Math.pow(2,14),nv=Math.pow(2,21),iv=Math.pow(2,28),ov=Math.pow(2,35),sv=Math.pow(2,42),av=Math.pow(2,49),cv=Math.pow(2,56),uv=Math.pow(2,63),Vt={encodingLength(t){return t<tv?1:t<rv?2:t<nv?3:t<iv?4:t<ov?5:t<sv?6:t<av?7:t<cv?8:t<uv?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=Dt(Vt.encodingLength(t))),fo.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return fo.fromBytes(t,e).toNumber(!0)}};var Fp=Symbol.for("@achingbrain/uint8arraylist");function Kp(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function Fs(t){return!!t?.[Fp]}var Xe=class t{constructor(...e){Object.defineProperty(this,Fp,{value:!0}),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 r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Fs(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Fs(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=Kp(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Kp(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(Fs(e))for(let n=0;n<e.length;n++)this.set(r+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,r){let{bufs:n,length:i}=this._subList(e,r);return Me(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Me(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),o=new t;return o.length=i,o.bufs=n,o}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(r===c){n.push(s);break}n.push(s.subarray(0,r-a));break}n.push(s)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!Fs(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(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let p=this.get(f+h);if(n[h]!==p){l=Math.max(1,h-a[p]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=Dt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=mr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=Dt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=mr(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=mr(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=mr(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Le(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};var qp={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var ho;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.publicKey!=null&&r.publicKey.byteLength>0&&(n.uint32(10),n.bytes(r.publicKey)),r.payloadType!=null&&r.payloadType.byteLength>0&&(n.uint32(18),n.bytes(r.payloadType)),r.payload!=null&&r.payload.byteLength>0&&(n.uint32(26),n.bytes(r.payload)),r.signature!=null&&r.signature.byteLength>0&&(n.uint32(42),n.bytes(r.signature)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(ho||(ho={}));var gi=class t{static createFromProtobuf=async e=>{let r=ho.decode(e),n=await pi(r.publicKey);return new t({peerId:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(e,r)=>{if(r.privateKey==null)throw new Error("Missing private key");let n=e.domain,i=e.codec,o=e.marshal(),s=Vp(n,i,o),c=await(await ui(r.privateKey)).sign(s.subarray());return new t({peerId:r,payloadType:i,payload:o,signature:c})};static openAndCertify=async(e,r)=>{let n=await t.createFromProtobuf(e);if(!await n.validate(r))throw new E("envelope signature is not valid for the given domain",qp.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:r,payloadType:n,payload:i,signature:o}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=ho.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Le(this.marshal(),e.marshal())}async validate(e){let r=Vp(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return so(this.peerId.publicKey).verify(r.subarray(),this.signature)}},Vp=(t,e,r)=>{let n=Y(t),i=Vt.encode(n.byteLength),o=Vt.encode(e.length),s=Vt.encode(r.length);return new Xe(i,n,o,e,s,r)};function $p(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var Ei=J(Mu(),1);var qs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=e,o+=l,o>u||(s+=1,r!==void 0&&s>r))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return r[i]=s[0],r[i+1]=s[1],r[i+2]=s[2],r[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];r[i]=o>>8,r[i+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jp=45,_v=15,xi=new qs;function Uu(t){if(!(t.length>_v))return xi.new(t).parseWith(()=>xi.readIPv4Addr())}function Ku(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>Jp))return xi.new(t).parseWith(()=>xi.readIPv6Addr())}function Vs(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>Jp))return xi.new(t).parseWith(()=>xi.readIPAddr())}var Z3=parseInt("0xFFFF",16),j3=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var cr=J(Mu(),1);function rm(t){return!!Uu(t)}function nm(t){return!!Ku(t)}function bi(t){return!!Vs(t)}var im=rm,Cv=nm,Fu=function(t){let e=0;if(t=t.toString().trim(),im(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Cv(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let o=im(r[n]),s;o&&(s=Fu(r[n]),r[n]=ee(s.slice(0,2),"base16")),s!=null&&++n<8&&r.splice(n,0,ee(s.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let o=parseInt(r[n],16);i[e++]=o>>8&255,i[e++]=o&255}return i}throw new Error("invalid ip address")},om=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let o=0;o<r;o++)i.push(t[e+o]);return i.join(".")}if(r===16){let i=[];for(let o=0;o<r;o+=2)i.push(n.getUint16(e+o).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wi={},qu={},Bv=[[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"],[777,-1,"memory"]];Bv.forEach(t=>{let e=Lv(...t);qu[e.code]=e,wi[e.name]=e});function Lv(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function we(t){if(typeof t=="number"){if(qu[t]!=null)return qu[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(wi[t]!=null)return wi[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var kT=we("ip4"),OT=we("ip6"),MT=we("ipcidr");function $u(t,e){switch(we(t).code){case 4:case 41:return Dv(e);case 42:return cm(e);case 6:case 273:case 33:case 132:return lm(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return cm(e);case 421:return Mv(e);case 444:return um(e);case 445:return um(e);case 466:return Ov(e);default:return ee(e,"base16")}}function zu(t,e){switch(we(t).code){case 4:return sm(e);case 41:return sm(e);case 42:return am(e);case 6:case 273:case 33:case 132:return Hu(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return am(e);case 421:return Nv(e);case 444:return Uv(e);case 445:return Kv(e);case 466:return kv(e);default:return Y(e,"base16")}}var Vu=Object.values(kr).map(t=>t.decoder),Pv=function(){let t=Vu[0].or(Vu[1]);return Vu.slice(2).forEach(e=>t=t.or(e)),t}();function sm(t){if(!bi(t))throw new Error("invalid ip address");return Fu(t)}function Dv(t){let e=om(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!bi(e))throw new Error("invalid ip address");return e}function Hu(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function lm(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function am(t){let e=Y(t),r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function cm(t){let e=cr.default.decode(t);if(t=t.slice(cr.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return ee(t)}function Nv(t){let e;t[0]==="Q"||t[0]==="1"?e=ln(Oe.decode(`z${t}`)).bytes:e=Pt.parse(t).multihash.bytes;let r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function kv(t){let e=Pv.decode(t),r=Uint8Array.from(cr.default.encode(e.length));return Me([r,e],r.length+e.length)}function Ov(t){let e=cr.default.decode(t),r=t.slice(cr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+ee(r,"base64url")}function Mv(t){let e=cr.default.decode(t),r=t.slice(cr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return ee(r,"base58btc")}function Uv(t){let e=t.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 r=mt.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 i=Hu(n);return Me([r,i],r.length+i.length)}function Kv(t){let e=t.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 r=mt.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 i=Hu(n);return Me([r,i],r.length+i.length)}function um(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=ee(e,"base32"),i=lm(r);return`${n}:${i}`}function fm(t){t=Gu(t);let e=[],r=[],n=null,i=t.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<i.length;o++){let s=i[o],a=we(s);if(a.size===0){e.push([a.code]),r.push([a.code]);continue}if(o++,o>=i.length)throw dm("invalid address: "+t);if(a.path===!0){n=Gu(i.slice(o).join("/")),e.push([a.code,zu(a.code,n)]),r.push([a.code,n]);break}let c=zu(a.code,i[o]);e.push([a.code,c]),r.push([a.code,$u(a.code,c)])}return{string:hm(r),bytes:Wu(e),tuples:e,stringTuples:r,path:n}}function Yu(t){let e=[],r=[],n=null,i=0;for(;i<t.length;){let o=Ei.default.decode(t,i),s=Ei.default.decode.bytes??0,a=we(o),c=Fv(a,t.slice(i+s));if(c===0){e.push([o]),r.push([o]),i+=s;continue}let u=t.slice(i+s,i+s+c);if(i+=c+s,i>t.length)throw dm("Invalid address Uint8Array: "+ee(t,"base16"));e.push([o,u]);let l=$u(o,u);if(r.push([o,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(t),string:hm(r),tuples:e,stringTuples:r,path:n}}function hm(t){let e=[];return t.map(r=>{let n=we(r[0]);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Gu(e.join("/"))}function Wu(t){return Me(t.map(e=>{let r=we(e[0]),n=Uint8Array.from(Ei.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=Me([n,e[1]])),n}))}function Fv(t,e){return t.size>0?t.size/8:t.size===0?0:Ei.default.decode(e)+(Ei.default.decode.bytes??0)}function Gu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function dm(t){return new Error("Error parsing address: "+t)}var qv=Symbol.for("nodejs.util.inspect.custom"),Vv=[we("dns").code,we("dns4").code,we("dns6").code,we("dnsaddr").code],Xu=new Map,pm=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Ln(t){return!!t?.[pm]}var Qu=class t{bytes;#e;#t;#r;#n;[pm]=!0;constructor(e){e==null&&(e="");let r;if(e instanceof Uint8Array)r=Yu(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);r=fm(e)}else if(Ln(e))r=Yu(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#e=r.string,this.#t=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,i,o="",s=we("tcp"),a=we("udp"),c=we("ip4"),u=we("ip6"),l=we("dns6"),f=we("ip6zone");for(let[p,d]of this.stringTuples())p===f.code&&(o=`%${d??""}`),Vv.includes(p)&&(r=s.name,i=443,n=`${d??""}${o}`,e=p===l.code?6:4),(p===s.code||p===a.code)&&(r=we(p).name,i=parseInt(d??"")),(p===c.code||p===u.code)&&(r=we(p).name,n=`${d??""}${o}`,e=p===u.code?6:4);if(e==null||r==null||n==null||i==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:r,port:i}}protos(){return this.#t.map(([e])=>Object.assign({},we(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>we(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new t(e),new t(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new t(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new t(Wu(r.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,i])=>{n===wi.p2p.code&&e.push([n,i]),n===wi["p2p-circuit"].code&&(e=[])});let r=e.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?ee(Oe.decode(`z${n}`),"base58btc"):ee(Pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return Le(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(o=>o.resolvable);if(r==null)return[this];let n=Xu.get(r.name);if(n==null)throw new E(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new t(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[qv](){return`Multiaddr(${this.#e})`}};function ze(t){return new Qu(t)}var mm="libp2p-peer-record",ym=Uint8Array.from([3,1]);var po;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=nt((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let a={multiaddr:new Uint8Array(0)},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(u&7);break}}return a})),i),n.encode=o=>rt(o,n.codec()),n.decode=o=>tt(o,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=nt((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=i==null?n.len:n.pos+i;for(;n.pos<s;){let a=n.uint32();switch(a>>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),r),t.encode=n=>rt(n,t.codec()),t.decode=n=>tt(n,t.codec())})(po||(po={}));var Pn=class t{static createFromProtobuf=e=>{let r=po.decode(e),n=di(r.peerId),i=(r.addresses??[]).map(s=>ze(s.multiaddr)),o=r.seq;return new t({peerId:n,multiaddrs:i,seqNumber:o})};static DOMAIN=mm;static CODEC=ym;peerId;multiaddrs;seqNumber;domain=t.DOMAIN;codec=t.CODEC;marshaled;constructor(e){let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=po.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof t)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!$p(this.multiaddrs,e.multiaddrs))}};function $v(t){return t[Symbol.asyncIterator]!=null}function zv(t){if($v(t))return(async()=>{let r=[];for await(let n of t)r.push(n);return r})();let e=[];for(let r of t)e.push(r);return e}var mo=zv;var Rm=J(xm(),1);var go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},ju=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},bm=t=>globalThis.DOMException===void 0?new ju(t):new DOMException(t),wm=t=>{let e=t.reason===void 0?bm("This operation was aborted."):t.reason;return e instanceof Error?e:bm(e)};function Ju(t,e,r,n){let i,o=new Promise((s,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(wm(c)),c.addEventListener("abort",()=>{a(wm(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new go(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{s(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return o.clear=()=>{clearTimeout(i),i=void 0},o}function el(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Dn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Rr,xo=class{constructor(){Rr.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Dn(this,Rr,"f")[this.size-1].priority>=r.priority){Dn(this,Rr,"f").push(n);return}let i=el(Dn(this,Rr,"f"),n,(o,s)=>s.priority-o.priority);Dn(this,Rr,"f").splice(i,0,n)}dequeue(){let e=Dn(this,Rr,"f").shift();return e?.run}filter(e){return Dn(this,Rr,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Dn(this,Rr,"f").length}};Rr=new WeakMap;var Pe=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},q=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ke,wo,Eo,Yr,Qs,vo,zs,$t,bo,wt,Hs,Et,_o,Gr,Gs,Em,vm,Sm,_m,Am,Ys,tl,rl,Xs,Im,Ws,Zs=class extends Error{},zt=class extends Rm.default{constructor(e){var r,n,i,o;if(super(),Ke.add(this),wo.set(this,void 0),Eo.set(this,void 0),Yr.set(this,0),Qs.set(this,void 0),vo.set(this,void 0),zs.set(this,0),$t.set(this,void 0),bo.set(this,void 0),wt.set(this,void 0),Hs.set(this,void 0),Et.set(this,0),_o.set(this,void 0),Gr.set(this,void 0),Gs.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(o=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);Pe(this,wo,e.carryoverConcurrencyCount,"f"),Pe(this,Eo,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Pe(this,Qs,e.intervalCap,"f"),Pe(this,vo,e.interval,"f"),Pe(this,wt,new e.queueClass,"f"),Pe(this,Hs,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Pe(this,Gs,e.throwOnTimeout===!0,"f"),Pe(this,Gr,e.autoStart===!1,"f")}get concurrency(){return q(this,_o,"f")}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})`);Pe(this,_o,e,"f"),q(this,Ke,"m",Xs).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:q(this,Gs,"f"),...r},new Promise((n,i)=>{q(this,wt,"f").enqueue(async()=>{var o,s,a;Pe(this,Et,(s=q(this,Et,"f"),s++,s),"f"),Pe(this,Yr,(a=q(this,Yr,"f"),a++,a),"f");try{if(!((o=r.signal)===null||o===void 0)&&o.aborted)throw new Zs("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=Ju(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,q(this,Ke,"m",Im).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof go&&!r.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{q(this,Ke,"m",Sm).call(this)}},r),this.emit("add"),q(this,Ke,"m",Ys).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return q(this,Gr,"f")?(Pe(this,Gr,!1,"f"),q(this,Ke,"m",Xs).call(this),this):this}pause(){Pe(this,Gr,!0,"f")}clear(){Pe(this,wt,new(q(this,Hs,"f")),"f")}async onEmpty(){q(this,wt,"f").size!==0&&await q(this,Ke,"m",Ws).call(this,"empty")}async onSizeLessThan(e){q(this,wt,"f").size<e||await q(this,Ke,"m",Ws).call(this,"next",()=>q(this,wt,"f").size<e)}async onIdle(){q(this,Et,"f")===0&&q(this,wt,"f").size===0||await q(this,Ke,"m",Ws).call(this,"idle")}get size(){return q(this,wt,"f").size}sizeBy(e){return q(this,wt,"f").filter(e).length}get pending(){return q(this,Et,"f")}get isPaused(){return q(this,Gr,"f")}};wo=new WeakMap,Eo=new WeakMap,Yr=new WeakMap,Qs=new WeakMap,vo=new WeakMap,zs=new WeakMap,$t=new WeakMap,bo=new WeakMap,wt=new WeakMap,Hs=new WeakMap,Et=new WeakMap,_o=new WeakMap,Gr=new WeakMap,Gs=new WeakMap,Ke=new WeakSet,Em=function(){return q(this,Eo,"f")||q(this,Yr,"f")<q(this,Qs,"f")},vm=function(){return q(this,Et,"f")<q(this,_o,"f")},Sm=function(){var e;Pe(this,Et,(e=q(this,Et,"f"),e--,e),"f"),q(this,Ke,"m",Ys).call(this),this.emit("next")},_m=function(){q(this,Ke,"m",rl).call(this),q(this,Ke,"m",tl).call(this),Pe(this,bo,void 0,"f")},Am=function(){let e=Date.now();if(q(this,$t,"f")===void 0){let r=q(this,zs,"f")-e;if(r<0)Pe(this,Yr,q(this,wo,"f")?q(this,Et,"f"):0,"f");else return q(this,bo,"f")===void 0&&Pe(this,bo,setTimeout(()=>{q(this,Ke,"m",_m).call(this)},r),"f"),!0}return!1},Ys=function(){if(q(this,wt,"f").size===0)return q(this,$t,"f")&&clearInterval(q(this,$t,"f")),Pe(this,$t,void 0,"f"),this.emit("empty"),q(this,Et,"f")===0&&this.emit("idle"),!1;if(!q(this,Gr,"f")){let e=!q(this,Ke,"a",Am);if(q(this,Ke,"a",Em)&&q(this,Ke,"a",vm)){let r=q(this,wt,"f").dequeue();return r?(this.emit("active"),r(),e&&q(this,Ke,"m",tl).call(this),!0):!1}}return!1},tl=function(){q(this,Eo,"f")||q(this,$t,"f")!==void 0||(Pe(this,$t,setInterval(()=>{q(this,Ke,"m",rl).call(this)},q(this,vo,"f")),"f"),Pe(this,zs,Date.now()+q(this,vo,"f"),"f"))},rl=function(){q(this,Yr,"f")===0&&q(this,Et,"f")===0&&q(this,$t,"f")&&(clearInterval(q(this,$t,"f")),Pe(this,$t,void 0,"f")),Pe(this,Yr,q(this,wo,"f")?q(this,Et,"f"):0,"f"),q(this,Ke,"m",Xs).call(this)},Xs=function(){for(;q(this,Ke,"m",Ys).call(this););},Im=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Zs("The task was aborted."))},{once:!0})})},Ws=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var nl=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Cm=t=>globalThis.DOMException===void 0?new il(t):new DOMException(t),Tm=t=>{let e=t.reason===void 0?Cm("This operation was aborted."):t.reason;return e instanceof Error?e:Cm(e)};function ol(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(e.signal){let{signal:h}=e;h.aborted&&l(Tm(h)),h.addEventListener("abort",()=>{l(Tm(h))})}if(r===Number.POSITIVE_INFINITY){t.then(u,l);return}let f=new nl;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){l(h)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?u():i instanceof Error?l(i):(f.message=i??`Promise timed out after ${r} milliseconds`,l(f))},r),(async()=>{try{u(await t)}catch(h){l(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}var sl="lock:worker:request-read",al="lock:worker:release-read",cl="lock:master:grant-read",ul="lock:worker:request-write",ll="lock:worker:release-write",fl="lock:master:grant-write";var Wr={},vi=t=>{t.addEventListener("message",e=>{vi.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{vi.dispatchEvent("message",t,e)})};vi.addEventListener=(t,e)=>{Wr[t]==null&&(Wr[t]=[]),Wr[t].push(e)};vi.removeEventListener=(t,e)=>{Wr[t]!=null&&(Wr[t]=Wr[t].filter(r=>r===e))};vi.dispatchEvent=function(t,e,r){Wr[t]!=null&&Wr[t].forEach(n=>n(e,r))};var hl=vi;var Bm=(t,e,r,n,i)=>(o,s)=>{if(s.data.type!==r)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(o.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",u),c())};o.addEventListener("message",u)}))}}))},Lm=(t,e,r,n)=>async()=>{let i=Ns();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(o=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",s),o(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",s)})},Yv={singleProcess:!1},Pm=t=>{if(t=Object.assign({},Yv,t),!!globalThis.document||t.singleProcess){let r=new EventTarget;return hl.addEventListener("message",Bm(r,"requestReadLock",sl,al,cl)),hl.addEventListener("message",Bm(r,"requestWriteLock",ul,ll,fl)),r}return{isWorker:!0,readLock:r=>Lm(r,sl,cl,al),writeLock:r=>Lm(r,ul,fl,ll)}};var Nn={},Qr;async function dl(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await ol((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var Wv=(t,e)=>{if(Qr.isWorker===!0)return{readLock:Qr.readLock(t,e),writeLock:Qr.writeLock(t,e)};let r=new zt({concurrency:1}),n;return{async readLock(){if(n!=null)return await dl(n,e);n=new zt({concurrency:e.concurrency,autoStart:!1});let i=n,o=dl(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await o},async writeLock(){return n=null,await dl(r,e)}}},Qv={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function pl(t){let e=Object.assign({},Qv,t);return Qr==null&&(Qr=Pm(e),Qr.isWorker!==!0&&(Qr.addEventListener("requestReadLock",r=>{Nn[r.data.name]!=null&&Nn[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Qr.addEventListener("requestWriteLock",async r=>{Nn[r.data.name]!=null&&Nn[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),Nn[e.name]==null&&(Nn[e.name]=Wv(e.name,e)),Nn[e.name]}var it={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var _i;(function(t){let e;(function(i){let o;i.codec=()=>(o==null&&(o=nt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=s.bytes();break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>rt(s,i.codec()),i.decode=s=>tt(s,i.codec())})(e=t.Peer$metadataEntry||(t.Peer$metadataEntry={}));let r;(function(i){let o;i.codec=()=>(o==null&&(o=nt((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),Js.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a)=>{let c={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:c.key=s.string();break;case 2:c.value=Js.codec().decode(s,s.uint32());break;default:s.skipType(l&7);break}}return c})),o),i.encode=s=>rt(s,i.codec()),i.decode=s=>tt(s,i.codec())})(r=t.Peer$tagsEntry||(t.Peer$tagsEntry={}));let n;t.codec=()=>(n==null&&(n=nt((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.addresses!=null)for(let a of i.addresses)o.uint32(10),js.codec().encode(a,o);if(i.protocols!=null)for(let a of i.protocols)o.uint32(18),o.string(a);if(i.publicKey!=null&&(o.uint32(34),o.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())o.uint32(50),t.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())o.uint32(58),t.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.addresses.push(js.codec().decode(i,i.uint32()));break;case 2:s.protocols.push(i.string());break;case 4:s.publicKey=i.bytes();break;case 5:s.peerRecordEnvelope=i.bytes();break;case 6:{let u=t.Peer$metadataEntry.codec().decode(i,i.uint32());s.metadata.set(u.key,u.value);break}case 7:{let u=t.Peer$tagsEntry.codec().decode(i,i.uint32());s.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return s})),n),t.encode=i=>rt(i,t.codec()),t.decode=i=>tt(i,t.codec())})(_i||(_i={}));var js;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.multiaddr!=null&&r.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(js||(js={}));var Js;(function(t){let e;t.codec=()=>(e==null&&(e=nt((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.value!=null&&r.value!==0&&(n.uint32(8),n.uint32(r.value)),r.expiry!=null&&(n.uint32(16),n.uint64(r.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={value:0},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.value=r.uint32();break;case 2:i.expiry=r.uint64();break;default:r.skipType(s&7);break}}return i})),e),t.encode=r=>rt(r,t.codec()),t.decode=r=>tt(r,t.codec())})(Js||(Js={}));function Ai(t,e){let r=_i.decode(e);r.publicKey!=null&&t.publicKey==null&&(t=mp({...t,publicKey:t.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[o,s]of r.tags.entries())s.expiry!=null&&s.expiry<i||n.set(o,s);return{...r,id:t,addresses:r.addresses.map(({multiaddr:o,isCertified:s})=>({multiaddr:ze(o),isCertified:s??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}var ml="/peers/";function Si(t){if(!Ds(t)||t.type==null)throw new E("Invalid PeerId",it.ERR_INVALID_PARAMETERS);let e=t.toCID().toString();return new sr(`${ml}${e}`)}async function Dm(t,e,r){let n=new Map;for(let i of r){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=ze(i.multiaddr)),!Ln(i.multiaddr))throw new E("Multiaddr was invalid",it.ERR_INVALID_PARAMETERS);if(!await e(t,i.multiaddr))continue;let o=i.isCertified??!1,s=i.multiaddr.toString(),a=n.get(s);a!=null?i.isCertified=a.isCertified||o:n.set(s,{multiaddr:i.multiaddr,isCertified:o})}return[...n.values()].sort((i,o)=>i.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:i,multiaddr:o})=>({isCertified:i,multiaddr:o.bytes}))}async function ta(t,e,r,n){if(e==null)throw new E("Invalid PeerData",it.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&t.publicKey!=null&&!Le(e.publicKey,t.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",it.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!t.equals(i.id))throw new E("peer id did not match existing peer id",it.ERR_INVALID_PARAMETERS);let o=i?.addresses??[],s=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(r==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ea(f,{validate:Nm})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ea(f,{validate:km,map:Om})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(r==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=ea([...a.entries()],{validate:Nm})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,d]of f)d==null?h.delete(p):h.set(p,d);c=ea([...h.entries()],{validate:km,map:Om})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await Dm(t,n.addressFilter??(async()=>!0),o),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??t.publicKey,peerRecordEnvelope:u};return t.type!=="RSA"&&delete l.publicKey,l}function ea(t,e){let r=new Map;for(let[n,i]of t)i!=null&&e.validate(n,i);for(let[n,i]of t.sort(([o],[s])=>o.localeCompare(s)))i!=null&&r.set(n,e.map?.(n,i)??i);return r}function Nm(t,e){if(typeof t!="string")throw new E("Metadata key must be a string",it.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",it.ERR_INVALID_PARAMETERS)}function km(t,e){if(typeof t!="string")throw new E("Tag name must be a string",it.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",it.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",it.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",it.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",it.ERR_INVALID_PARAMETERS)}}function Om(t,e){let r;return e.expiry!=null&&(r=e.expiry),e.ttl!=null&&(r=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:r}}function ra(t,e,r){let n=t.toString().split("/")[2],i=mt.decode(n),o=di(i),s=r.get(o);if(s!=null)return s;let a=Ai(o,e);return r.set(o,a),a}function Xv(t,e){return t==null?{}:{prefix:ml,filters:(t.filters??[]).map(r=>({key:n,value:i})=>r(ra(n,i,e))),orders:(t.orders??[]).map(r=>(n,i)=>r(ra(n.key,n.value,e),ra(i.key,i.value,e)))}}var na=class{peerId;datastore;lock;addressFilter;constructor(e,r={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=r.addressFilter,this.lock=pl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Si(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",it.ERR_INVALID_PARAMETERS);await this.datastore.delete(Si(e))}async load(e){let r=await this.datastore.get(Si(e));return Ai(e,r)}async save(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,i)}async patch(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,n,i)}async merge(e,r){let{existingBuf:n,existingPeer:i}=await this.#e(e),o=await ta(e,r,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,n,i)}async*all(e){let r=new qt;for await(let{key:n,value:i}of this.datastore.query(Xv(e??{},r))){let o=ra(n,i,r);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let r=await this.datastore.get(Si(e)),n=Ai(e,r);return{existingBuf:r,existingPeer:n}}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}return{}}async#t(e,r,n,i){let o=_i.encode(r);return n!=null&&Le(o,n)?{peer:Ai(e,o),previous:i,updated:!1}:(await this.datastore.put(Si(e),o),{peer:Ai(e,o),previous:i,updated:!0})}};var _e=ie("libp2p:peer-store"),ia=class{store;events;peerId;constructor(e,r={}){this.events=e.events,this.peerId=e.peerId,this.store=new na(e,r)}async forEach(e,r){_e.trace("forEach await read lock");let n=await this.store.lock.readLock();_e.trace("forEach got read lock");try{for await(let i of this.store.all(r))e(i)}finally{_e.trace("forEach release read lock"),n()}}async all(e){_e.trace("all await read lock");let r=await this.store.lock.readLock();_e.trace("all got read lock");try{return await mo(this.store.all(e))}finally{_e.trace("all release read lock"),r()}}async delete(e){_e.trace("delete await write lock");let r=await this.store.lock.writeLock();_e.trace("delete got write lock");try{await this.store.delete(e)}finally{_e.trace("delete release write lock"),r()}}async has(e){_e.trace("has await read lock");let r=await this.store.lock.readLock();_e.trace("has got read lock");try{return await this.store.has(e)}finally{_e.trace("has release read lock"),r()}}async get(e){_e.trace("get await read lock");let r=await this.store.lock.readLock();_e.trace("get got read lock");try{return await this.store.load(e)}finally{_e.trace("get release read lock"),r()}}async save(e,r){_e.trace("save await write lock");let n=await this.store.lock.writeLock();_e.trace("save got write lock");try{let i=await this.store.save(e,r);return this.#e(e,i),i.peer}finally{_e.trace("save release write lock"),n()}}async patch(e,r){_e.trace("patch await write lock");let n=await this.store.lock.writeLock();_e.trace("patch got write lock");try{let i=await this.store.patch(e,r);return this.#e(e,i),i.peer}finally{_e.trace("patch release write lock"),n()}}async merge(e,r){_e.trace("merge await write lock");let n=await this.store.lock.writeLock();_e.trace("merge got write lock");try{let i=await this.store.merge(e,r);return this.#e(e,i),i.peer}finally{_e.trace("merge release write lock"),n()}}async consumePeerRecord(e,r){let n=await gi.openAndCertify(e,Pn.DOMAIN);if(r?.equals(n.peerId)===!1)return _e("envelope peer id was not the expected peer id - expected: %p received: %p",r,n.peerId),!1;let i=Pn.createFromProtobuf(n.payload),o;try{o=await this.get(n.peerId)}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}if(o?.peerRecordEnvelope!=null){let s=await gi.createFromProtobuf(o.peerRecordEnvelope),a=Pn.createFromProtobuf(s.payload);if(a.seqNumber>=i.seqNumber)return _e("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(s=>({isCertified:!0,multiaddr:s}))}),!0}#e(e,r){r.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:r}):this.events.safeDispatchEvent("peer:update",{detail:r}))}};function Zv(t){return t[Symbol.asyncIterator]!=null}function jv(t){if(Zv(t))return(async()=>{for await(let e of t);})();for(let e of t);}var yl=jv;function Jv(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var oa=Jv;function e_(t){return t[Symbol.asyncIterator]!=null}function t_(t,e){if(e_(t))return async function*(){for await(let a of t)await e(a)&&(yield a)}();let r=oa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of r)await e(a)&&(yield a)}();let s=e;return function*(){o===!0&&(yield n);for(let a of r)s(a)&&(yield a)}()}var Ht=t_;function r_(t){return t[Symbol.asyncIterator]!=null}function n_(t,e){return r_(t)?async function*(){yield*(await mo(t)).sort(e)}():function*(){yield*mo(t).sort(e)}()}var gl=n_;function i_(t){return t[Symbol.asyncIterator]!=null}function o_(t,e){return i_(t)?async function*(){let r=0;if(!(e<1)){for await(let n of t)if(yield n,r++,r===e)return}}():function*(){let r=0;if(!(e<1)){for(let n of t)if(yield n,r++,r===e)return}}()}var xl=o_;var sa=class{put(e,r,n){return Promise.reject(new Error(".put is not implemented"))}get(e,r){return Promise.reject(new Error(".get is not implemented"))}has(e,r){return Promise.reject(new Error(".has is not implemented"))}delete(e,r){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,r={}){for await(let{key:n,value:i}of e)await this.put(n,i,r),yield n}async*getMany(e,r={}){for await(let n of e)yield{key:n,value:await this.get(n,r)}}async*deleteMany(e,r={}){for await(let n of e)await this.delete(n,r),yield n}batch(){let e=[],r=[];return{put(n,i){e.push({key:n,value:i})},delete(n){r.push(n)},commit:async n=>{await yl(this.putMany(e,n)),e=[],await yl(this.deleteMany(r,n)),r=[]}}}async*_all(e,r){throw new Error("._all is not implemented")}async*_allKeys(e,r){throw new Error("._allKeys is not implemented")}query(e,r){let n=this._all(e,r);if(e.prefix!=null){let i=e.prefix;n=Ht(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Ht(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>gl(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=Ht(n,()=>i++>=o)}return e.limit!=null&&(n=xl(n,e.limit)),n}queryKeys(e,r){let n=this._allKeys(e,r);if(e.prefix!=null){let i=e.prefix;n=Ht(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>Ht(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>gl(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=Ht(n,()=>o++>=i)}return e.limit!=null&&(n=xl(n,e.limit)),n}};var Km=J(bl(),1);function Fm(t){return t=t??new Error("Not Found"),(0,Km.default)(t,"ERR_NOT_FOUND")}var aa=class extends sa{data;constructor(){super(),this.data=new Map}put(e,r){return this.data.set(e.toString(),r),e}get(e){let r=this.data.get(e.toString());if(r==null)throw Fm();return r}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,r]of this.data.entries())yield{key:new sr(e),value:r}}*_allKeys(){for(let e of this.data.keys())yield new sr(e)}};function qm(t,e){let r;return function(){let n=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(n,e)}}var c_=ie("libp2p:address-manager"),u_=t=>t;function wl(t,e){let r=t.getPeerId();return r!=null&&pe(r).equals(e)&&(t=t.decapsulate(ze(`/p2p/${e.toString()}`))),t}var ca=class{components;listen;announce;observed;announceFilter;constructor(e,r={}){let{listen:n=[],announce:i=[]}=r;this.components=e,this.listen=n.map(o=>o.toString()),this.announce=new Set(i.map(o=>o.toString())),this.observed=new Map,this.announceFilter=r.announceFilter??u_,this._updatePeerStoreAddresses=qm(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([r,n])=>n.confident).map(([r])=>ze(r))).map(r=>r.getPeerId()===this.components.peerId.toString()?r.decapsulate(`/p2p/${this.components.peerId.toString()}`):r);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(r=>{c_.error("error updating addresses",r)})}getListenAddrs(){return Array.from(this.listen).map(e=>ze(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ze(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ze(e))}addObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString();this.observed.has(r)||this.observed.set(r,{confident:!1})}confirmObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString(),i=(this.observed.get(r)??{confident:!1}).confident;this.observed.set(r,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=wl(e,this.components.peerId);let r=e.toString();this.observed.delete(r)}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,i])=>i.confident).map(([n])=>n));let r=new Set(e);return this.announceFilter(Array.from(r).map(n=>ze(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function Vm(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}var El=class{components={};_started=!1;constructor(e={}){this.components={};for(let[r,n]of Object.entries(e))this.components[r]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(r=>Vm(r)).map(async r=>{await r[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")}},l_=["metrics","connectionProtector"],f_=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function $m(t={}){let e=new El(t);return new Proxy(e,{get(n,i,o){if(typeof i=="string"&&!f_.includes(i)){let s=e.components[i];if(s==null&&!l_.includes(i))throw new E(`${i} not set`,"ERR_SERVICE_MISSING");return s}return Reflect.get(n,i,o)},set(n,i,o){return typeof i=="string"?e.components[i]=o:Reflect.set(n,i,o),!0}})}var Xm=J(zm(),1);var Hm="[a-fA-F\\d:]",Xr=t=>t&&t.includeBoundaries?`(?:(?<=\\s|^)(?=${Hm})|(?<=${Hm})(?=\\s|$))`:"",Gt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",qe="[a-fA-F\\d]{1,4}",ua=`
38
38
  (?:
39
39
  (?:${qe}:){7}(?:${qe}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
40
40
  (?:${qe}:){6}(?:${Gt}|:${qe}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
@@ -45,7 +45,7 @@
45
45
  (?:${qe}:){1}(?:(?::${qe}){0,4}:${Gt}|(?::${qe}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
46
46
  (?::(?:(?::${qe}){0,5}:${Gt}|(?::${qe}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
47
47
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
48
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),h_=new RegExp(`(?:^${Gt}$)|(?:^${ua}$)`),d_=new RegExp(`^${Gt}$`),p_=new RegExp(`^${ua}$`),vl=t=>t&&t.exact?h_:new RegExp(`(?:${Xr(t)}${Gt}${Xr(t)})|(?:${Xr(t)}${ua}${Xr(t)})`,"g");vl.v4=t=>t&&t.exact?d_:new RegExp(`${Xr(t)}${Gt}${Xr(t)}`,"g");vl.v6=t=>t&&t.exact?p_:new RegExp(`${Xr(t)}${ua}${Xr(t)}`,"g");var Gm=vl;var Zm=J(Wm(),1),{isValid:m_,parse:y_}=Zm.default,g_=["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"],x_=g_.map(t=>new Xm.Netmask(t));function b_(t){for(let e of x_)if(e.contains(t))return!0;return!1}function Qm(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var jm=t=>{if(m_(t)){let e=y_(t);if(e.kind()==="ipv4")return b_(e.toNormalizedString());if(e.kind()==="ipv6")return Qm(t)}else if(bi(t)&&Gm.v6().test(t))return Qm(t)};var fa=jm;function Jm(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!fa(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var t6=Symbol.for("@libp2p/transport");var Zr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Zr||(Zr={}));function _l(t){try{let{address:e}=t.nodeAddress();return!!fa(e)}catch{return!0}}function Ii(t,e){let r=_l(t.multiaddr),n=_l(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var Sl=J(Ru(),1),Il=J(ry(),1);var ny=globalThis.fetch,iy=globalThis.Headers,c6=globalThis.Request,u6=globalThis.Response;function ha(t,e,r){return`${t}?name=${e}&type=${r}`}async function oy(t,e){return await(await ny(t,{headers:new iy({accept:"application/dns-json"}),signal:e})).json()}function kn(t,e){return`${e}_${t}`}var Al=Object.assign((0,Sl.default)("dns-over-http-resolver"),{error:(0,Sl.default)("dns-over-http-resolver:error")}),Rl=class{constructor(e={}){this._cache=new Il.default({max:e?.maxCache??100}),this._TXTcache=new Il.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??oy,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},sy=Rl;var ay=sy;var{code:A_}=we("dnsaddr");async function Ri(t,e={}){let r=new ay;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===A_)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var ur;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(ur||(ur={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var S_={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ri},addressSorter:Ii},transportManager:{faultTolerance:Zr.FATAL_ALL}};function cy(t){let e=zr(S_,t);if(e.transports==null||e.transports.length<1)throw new E(ur.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(ur.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var uy="keep-alive";var cg=J(ig(),1);var aA=ie("libp2p:get-peer");function pa(t){if(Ds(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:pe(r),t.forEach(n=>{if(!Ln(n))throw aA.error("multiaddr %s was invalid",n),new E("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let o=pe(i);if(e==null||!e.equals(o))throw new E("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function cA(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Vl=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new E("missing peer id",F.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=cA(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},ma=class extends zt{constructor(e={}){super({...e,queueClass:Vl})}hasJob(e){return this.sizeBy({peerId:e})>0}};var ot=ie("libp2p:connection-manager:auto-dial"),Io={minConnections:50,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},ya=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Io.minConnections,this.autoDialPriority=r.autoDialPriority??Io.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Io.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Io.maxQueueLength,this.started=!1,this.running=!1,this.queue=new ma({concurrency:r.autoDialConcurrency??Io.autoDialConcurrency}),this.queue.addListener("error",n=>{ot.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{ot.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{ot.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{ot.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&ot.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){ot("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){ot("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,ot("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new Bn(this.connectionManager.getDialQueue().map(c=>c.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[c=>c.addresses.length===0?(ot.trace("not autodialing %p because they have no addresses"),!1):e.has(c.id)?(ot.trace("not autodialing %p because they are already connected"),!1):n.has(c.id)?(ot.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(c.id)?(ot.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new qt;for(let c of o)s.has(c.id)||s.set(c.id,[...c.tags.values()].reduce((u,l)=>u+l.value,0));let a=o.sort((c,u)=>{let l=s.get(c.id)??0,f=s.get(u.id)??0;return l>f?-1:l<f?1:0});ot("selected %d/%d peers to dial",a.length,i.length);for(let c of a)this.queue.add(async()=>{let u=this.connectionManager.getConnectionsMap().size;if(u>=this.minConnections){ot("got enough connections now %d/%d",u,this.minConnections),this.queue.clear();return}ot("connecting to a peerStore stored peer %p",c.id),await this.connectionManager.openConnection(c.id,{priority:this.autoDialPriority})},{peerId:c.id}).catch(u=>{ot.error("could not connect to peerStore stored peer",u)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(c=>{ot.error("error while autodialing",c)})},this.autoDialIntervalMs))}};var Pi=ie("libp2p:connection-manager:connection-pruner"),og={maxConnections:300,allow:[]},ga=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??og.maxConnections,this.allow=r.allow??og.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Pi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Pi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Pi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new qt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Pi.error("error loading peer tags",u)}}}let o=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),s=[];for(let a of o)if(Pi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Pi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var Xl=J($n(),1);function Di(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function Jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Wl=J($n(),1);var sg=ie("libp2p:connection-manager:utils");async function Ql(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await lA(t,e),s=(await Promise.all(n.map(async a=>Ql(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return sg("resolved %s to",t,s.map(a=>a.toString())),s}async function lA(t,e){try{return t=ze(t.toString()),await t.resolve(e)}catch(r){return sg.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function ag(...t){let e=[];for(let n of t)if(n!=null){try{(0,Wl.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Di(e);try{(0,Wl.setMaxListeners)?.(1/0,r)}catch{}return r}var ct=ie("libp2p:connection-manager:dial-queue"),Ro={addressSorter:Ii,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Ri}},xa=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Ro.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Ro.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Ro.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Ro.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,Xl.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))Xu.set(n,i);this.queue=new zt({concurrency:r.maxParallelDials??Ro.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{ct.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=pa(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return ct("joining existing dial target for %p",n),s.clear(),c.promise;ct("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:hA(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(l=>{throw ct.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),s.aborted?new E(l.message,F.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Di([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,Xl.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new E("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){ct("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),ct("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Ql(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),o=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),s=new Map;for(let l of o){let f=l.multiaddr.toString(),h=s.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(ct("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),ct("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new E("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new E("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new E("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new zt({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{ct.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new E("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=ag(c.signal,r.signal);u.addEventListener("abort",()=>{ct("dial to %a aborted",s)});let l=Jr();return await i.add(async()=>{if(u.aborted){ct("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new Wn);return}await this.queue.add(async()=>{try{if(u.aborted){ct("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new Wn);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){ct("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{ct.error("error closing superfluous connection",h)}),l.reject(new Wn);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),ct("dial to %a succeeded",s),l.resolve(f)}catch(f){ct.error("error during dial of %a",s,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(o==null)throw new E("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function hA(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _t=ie("libp2p:connection-manager"),mA=50,On={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},ba=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??On.maxConnections;let n=r.minConnections??On.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new qt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,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=(r.allow??[]).map(i=>ze(i)),this.deny=(r.deny??[]).map(i=>ze(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??On.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new cg.RateLimiterMemory({points:r.inboundConnectionThreshold??On.inboundConnectionThreshold,duration:1}),this.autoDial=new ya({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??On.autoDialConcurrency,autoDialPriority:r.autoDialPriority??On.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??On.autoDialMaxQueueLength}),this.connectionPruner=new ga({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new xa({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Ii,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ri}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,_t("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(uy)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{_t.error(n)})}))}).catch(e=>{_t.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){_t.error(i)}})());_t("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),_t("stopped")}onConnect(e){this._onConnect(e).catch(r=>{_t.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new E("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=pa(e);if(n!=null){_t("dial %p",n);let a=this.getConnections(n);if(a.length>0)return _t("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??mA}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return _t("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return _t("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return _t("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(_t("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var wa=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}},Ni=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new wa(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 r=this.head;this.head=r.next=new wa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ef=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Mn(t={}){return yA(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function yA(t,e){e=e??{};let r=e.onEnd,n=new Ni,i,o,s,a=Jr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(w){g(w)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Jr()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Ni,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)return i;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})},h=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Ni,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((C,_)=>{w=()=>{_(new ef)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function gA(t){return t[Symbol.asyncIterator]!=null}function xA(...t){let e=[];for(let r of t)gA(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Mn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var en=xA;function Un(t,...e){if(t==null)throw new Error("Empty pipeline");if(tf(t)){let n=t;t=()=>n.source}else if(lg(t)||ug(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&tf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)tf(r[n])&&(r[n]=wA(r[n]));return bA(...r)}var bA=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},ug=t=>t?.[Symbol.asyncIterator]!=null,lg=t=>t?.[Symbol.iterator]!=null,tf=t=>t==null?!1:t.sink!=null&&t.source!=null,wA=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Mn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(ug(o))i=async function*(){yield*o,n.end()};else if(lg(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return en(n,i())}return t.source};function EA(t){return t[Symbol.asyncIterator]!=null}function vA(t,e){if(EA(t))return async function*(){for await(let a of t)yield e(a)}();let r=oa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var fg=vA;async function*Co(t,e){yield*fg(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ea(t){let e=new Set;return Ht(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*va(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new E(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var _a=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new E("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*Un(en(...this.routers.map(n=>n.findProviders(e,r))),n=>Co(n,this.components.peerStore),n=>Ea(n),n=>va(n))}async provide(e,r={}){if(this.routers.length===0)throw new E("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new E(ur.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new E(ur.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function _A(t){return t[Symbol.asyncIterator]!=null}function AA(t){if(_A(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Aa=AA;var SA=ie("libp2p:peer-routing"),Sa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new E("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new E("Should not try to find self",F.ERR_FIND_SELF);let n=await Un(en(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){SA.error(o)}}())),i=>Ht(i,Boolean),i=>Co(i,this.components.peerStore),async i=>Aa(i));if(n!=null)return n;throw new E(ur.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new E("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*Un(en(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Co(n,this.components.peerStore),n=>Ea(n),n=>va(n))}};var rf=ie("libp2p:registrar"),nf=32,of=64,Ia=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new E(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=zr.bind({ignoreUndefined:!0})({maxInboundStreams:nf,maxOutboundStreams:of},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(r==null)throw new E("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&rf.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){rf("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&rf.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var sf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function hg(t){let{name:e,metrics:r}=t,n;return r!=null?n=new sf({name:e,metrics:r}):n=new Map,n}var Kn=ie("libp2p:transports"),Ra=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=hg({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Zr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new E("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new E(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);Kn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}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[r,n]of this.listeners)for(Kn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Kn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new E("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){Kn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Kn("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Zr.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Zr.FATAL_ALL)throw new E(n,F.ERR_NO_VALID_ADDRESSES);Kn(`libp2p in dial mode only: ${n}`)}}async remove(e){Kn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var lf=J($n(),1);var Cr="/multistream/1.0.0";function af(t){let e=async function*(){let r=yield,n=new Xe;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Xe;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Xe);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ca(t){let e=Mn(),r=af(t.source),n=Jr(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var To=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function dg(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Ta(t,e,r){let n=r??{},i=dg(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new To(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:p}=n;f(new To(h,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function IA(t,e,r){return n=>t(Ta(n,e,r))}function pg(t,e,r){return{sink:IA(t.sink,e,{...r,onAbort:void 0}),source:Ta(t.source,e,r)}}function Ba(t){return t[Symbol.asyncIterator]!=null}var La=t=>{let e=Vt.encodingLength(t),r=Dt(e);return Vt.encode(t,r),La.bytes=e,r};La.bytes=0;function Pa(t,e){e=e??{};let r=e.lengthEncoder??La;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Ba(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Pa.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??La;return new Xe(r(t.byteLength),t)};var ki=J(bl(),1);var RA=8,CA=1024*1024*4,Fn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Fn||(Fn={}));var cf=t=>{let e=Vt.decode(t);return cf.bytes=Vt.encodingLength(e),e};cf.bytes=0;function Bo(t,e){let r=new Xe,n=Fn.LENGTH,i=-1,o=e?.lengthDecoder??cf,s=e?.maxLengthLength??RA,a=e?.maxDataLength??CA;function*c(){for(;r.byteLength>0;){if(n===Fn.LENGTH)try{if(i=o(r),i<0)throw(0,ki.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,ki.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Fn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,ki.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Fn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Fn.LENGTH}}}return Ba(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ki.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ki.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Bo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Bo(n,{...e??{},onLength:o=>{r=o}})};var LA=ie("libp2p:mss"),mg=Y(`
48
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),h_=new RegExp(`(?:^${Gt}$)|(?:^${ua}$)`),d_=new RegExp(`^${Gt}$`),p_=new RegExp(`^${ua}$`),vl=t=>t&&t.exact?h_:new RegExp(`(?:${Xr(t)}${Gt}${Xr(t)})|(?:${Xr(t)}${ua}${Xr(t)})`,"g");vl.v4=t=>t&&t.exact?d_:new RegExp(`${Xr(t)}${Gt}${Xr(t)}`,"g");vl.v6=t=>t&&t.exact?p_:new RegExp(`${Xr(t)}${ua}${Xr(t)}`,"g");var Gm=vl;var Zm=J(Wm(),1),{isValid:m_,parse:y_}=Zm.default,g_=["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"],x_=g_.map(t=>new Xm.Netmask(t));function b_(t){for(let e of x_)if(e.contains(t))return!0;return!1}function Qm(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var jm=t=>{if(m_(t)){let e=y_(t);if(e.kind()==="ipv4")return b_(e.toNormalizedString());if(e.kind()==="ipv6")return Qm(t)}else if(bi(t)&&Gm.v6().test(t))return Qm(t)};var fa=jm;function Jm(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!fa(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var t6=Symbol.for("@libp2p/transport");var Zr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Zr||(Zr={}));function _l(t){try{let{address:e}=t.nodeAddress();return!!fa(e)}catch{return!0}}function Ii(t,e){let r=_l(t.multiaddr),n=_l(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var Sl=J(Ru(),1),Il=J(ry(),1);var ny=globalThis.fetch,iy=globalThis.Headers,c6=globalThis.Request,u6=globalThis.Response;function ha(t,e,r){return`${t}?name=${e}&type=${r}`}async function oy(t,e){return await(await ny(t,{headers:new iy({accept:"application/dns-json"}),signal:e})).json()}function kn(t,e){return`${e}_${t}`}var Al=Object.assign((0,Sl.default)("dns-over-http-resolver"),{error:(0,Sl.default)("dns-over-http-resolver:error")}),Rl=class{constructor(e={}){this._cache=new Il.default({max:e?.maxCache??100}),this._TXTcache=new Il.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??oy,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(kn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(ha(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(kn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Al.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},sy=Rl;var ay=sy;var{code:A_}=we("dnsaddr");async function Ri(t,e={}){let r=new ay;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===A_)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var ur;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(ur||(ur={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var S_={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ri},addressSorter:Ii},transportManager:{faultTolerance:Zr.FATAL_ALL}};function cy(t){let e=zr(S_,t);if(e.transports==null||e.transports.length<1)throw new E(ur.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(ur.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var uy="keep-alive";var cg=J(ig(),1);var aA=ie("libp2p:get-peer");function pa(t){if(Ds(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:pe(r),t.forEach(n=>{if(!Ln(n))throw aA.error("multiaddr %s was invalid",n),new E("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let o=pe(i);if(e==null||!e.equals(o))throw new E("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function cA(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Vl=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new E("missing peer id",F.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=cA(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},ma=class extends zt{constructor(e={}){super({...e,queueClass:Vl})}hasJob(e){return this.sizeBy({peerId:e})>0}};var ot=ie("libp2p:connection-manager:auto-dial"),Io={minConnections:50,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},ya=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Io.minConnections,this.autoDialPriority=r.autoDialPriority??Io.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Io.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Io.maxQueueLength,this.started=!1,this.running=!1,this.queue=new ma({concurrency:r.autoDialConcurrency??Io.autoDialConcurrency}),this.queue.addListener("error",n=>{ot.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{ot.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{ot.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{ot.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&ot.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){ot("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){ot("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,ot("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new Bn(this.connectionManager.getDialQueue().map(c=>c.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[c=>c.addresses.length===0?(ot.trace("not autodialing %p because they have no addresses"),!1):e.has(c.id)?(ot.trace("not autodialing %p because they are already connected"),!1):n.has(c.id)?(ot.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(c.id)?(ot.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new qt;for(let c of o)s.has(c.id)||s.set(c.id,[...c.tags.values()].reduce((u,l)=>u+l.value,0));let a=o.sort((c,u)=>{let l=s.get(c.id)??0,f=s.get(u.id)??0;return l>f?-1:l<f?1:0});ot("selected %d/%d peers to dial",a.length,i.length);for(let c of a)this.queue.add(async()=>{let u=this.connectionManager.getConnectionsMap().size;if(u>=this.minConnections){ot("got enough connections now %d/%d",u,this.minConnections),this.queue.clear();return}ot("connecting to a peerStore stored peer %p",c.id),await this.connectionManager.openConnection(c.id,{priority:this.autoDialPriority})},{peerId:c.id}).catch(u=>{ot.error("could not connect to peerStore stored peer",u)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(c=>{ot.error("error while autodialing",c)})},this.autoDialIntervalMs))}};var Pi=ie("libp2p:connection-manager:connection-pruner"),og={maxConnections:300,allow:[]},ga=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??og.maxConnections,this.allow=r.allow??og.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Pi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Pi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Pi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new qt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Pi.error("error loading peer tags",u)}}}let o=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),s=[];for(let a of o)if(Pi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Pi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var Xl=J($n(),1);function Di(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function Jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Wl=J($n(),1);var sg=ie("libp2p:connection-manager:utils");async function Ql(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await lA(t,e),s=(await Promise.all(n.map(async a=>Ql(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return sg("resolved %s to",t,s.map(a=>a.toString())),s}async function lA(t,e){try{return t=ze(t.toString()),await t.resolve(e)}catch(r){return sg.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function ag(...t){let e=[];for(let n of t)if(n!=null){try{(0,Wl.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Di(e);try{(0,Wl.setMaxListeners)?.(1/0,r)}catch{}return r}var ct=ie("libp2p:connection-manager:dial-queue"),Ro={addressSorter:Ii,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Ri}},xa=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Ro.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Ro.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Ro.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Ro.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,Xl.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))Xu.set(n,i);this.queue=new zt({concurrency:r.maxParallelDials??Ro.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{ct.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=pa(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return ct("joining existing dial target for %p",n),s.clear(),c.promise;ct("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:hA(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(l=>{throw ct.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),s.aborted?new E(l.message,F.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Di([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,Xl.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new E("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){ct("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),ct("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Ql(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat(),o=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),s=new Map;for(let l of o){let f=l.multiaddr.toString(),h=s.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(ct("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),ct("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new E("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new E("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let h=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:h!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new E("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new zt({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{ct.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new E("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=ag(c.signal,r.signal);u.addEventListener("abort",()=>{ct("dial to %a aborted",s)});let l=Jr();return await i.add(async()=>{if(u.aborted){ct("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new Wn);return}await this.queue.add(async()=>{try{if(u.aborted){ct("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new Wn);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){ct("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{ct.error("error closing superfluous connection",h)}),l.reject(new Wn);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),ct("dial to %a succeeded",s),l.resolve(f)}catch(f){ct.error("error during dial of %a",s,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(o==null)throw new E("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function hA(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _t=ie("libp2p:connection-manager"),mA=50,On={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},ba=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??On.maxConnections;let n=r.minConnections??On.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new qt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,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=(r.allow??[]).map(i=>ze(i)),this.deny=(r.deny??[]).map(i=>ze(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??On.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new cg.RateLimiterMemory({points:r.inboundConnectionThreshold??On.inboundConnectionThreshold,duration:1}),this.autoDial=new ya({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??On.autoDialConcurrency,autoDialPriority:r.autoDialPriority??On.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??On.autoDialMaxQueueLength}),this.connectionPruner=new ga({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new xa({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Ii,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ri}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,_t("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(uy)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{_t.error(n)})}))}).catch(e=>{_t.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){_t.error(i)}})());_t("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),_t("stopped")}onConnect(e){this._onConnect(e).catch(r=>{_t.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new E("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=pa(e);if(n!=null){_t("dial %p",n);let a=this.getConnections(n);if(a.length>0)return _t("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??mA}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return _t("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return _t("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return _t("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(_t("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var wa=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}},Ni=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new wa(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 r=this.head;this.head=r.next=new wa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ef=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Mn(t={}){return yA(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function yA(t,e){e=e??{};let r=e.onEnd,n=new Ni,i,o,s,a=Jr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(w){g(w)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Jr()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Ni,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)return i;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})},h=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Ni,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((C,_)=>{w=()=>{_(new ef)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function gA(t){return t[Symbol.asyncIterator]!=null}function xA(...t){let e=[];for(let r of t)gA(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Mn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var en=xA;function Un(t,...e){if(t==null)throw new Error("Empty pipeline");if(tf(t)){let n=t;t=()=>n.source}else if(lg(t)||ug(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&tf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)tf(r[n])&&(r[n]=wA(r[n]));return bA(...r)}var bA=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},ug=t=>t?.[Symbol.asyncIterator]!=null,lg=t=>t?.[Symbol.iterator]!=null,tf=t=>t==null?!1:t.sink!=null&&t.source!=null,wA=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Mn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(ug(o))i=async function*(){yield*o,n.end()};else if(lg(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return en(n,i())}return t.source};function EA(t){return t[Symbol.asyncIterator]!=null}function vA(t,e){if(EA(t))return async function*(){for await(let a of t)yield e(a)}();let r=oa(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var fg=vA;async function*Co(t,e){yield*fg(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ea(t){let e=new Set;return Ht(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*va(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new E(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var _a=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new E("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*Un(en(...this.routers.map(n=>n.findProviders(e,r))),n=>Co(n,this.components.peerStore),n=>Ea(n),n=>va(n))}async provide(e,r={}){if(this.routers.length===0)throw new E("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new E(ur.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new E(ur.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function _A(t){return t[Symbol.asyncIterator]!=null}function AA(t){if(_A(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Aa=AA;var SA=ie("libp2p:peer-routing"),Sa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new E("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new E("Should not try to find self",F.ERR_FIND_SELF);let n=await Un(en(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){SA.error(o)}}())),i=>Ht(i,Boolean),i=>Co(i,this.components.peerStore),async i=>Aa(i));if(n!=null)return n;throw new E(ur.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new E("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*Un(en(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Co(n,this.components.peerStore),n=>Ea(n),n=>va(n))}};var rf=ie("libp2p:registrar"),nf=32,of=64,Ia=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new E(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=zr.bind({ignoreUndefined:!0})({maxInboundStreams:nf,maxOutboundStreams:of},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(r==null)throw new E("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&rf.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){rf("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&rf.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var sf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function hg(t){let{name:e,metrics:r}=t,n;return r!=null?n=new sf({name:e,metrics:r}):n=new Map,n}var Kn=ie("libp2p:transports"),Ra=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=hg({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Zr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new E("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new E(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);Kn("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}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[r,n]of this.listeners)for(Kn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Kn("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new E("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){Kn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Kn("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Zr.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Zr.FATAL_ALL)throw new E(n,F.ERR_NO_VALID_ADDRESSES);Kn(`libp2p in dial mode only: ${n}`)}}async remove(e){Kn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var lf=J($n(),1);var Cr="/multistream/1.0.0";function af(t){let e=async function*(){let r=yield,n=new Xe;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Xe;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Xe);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ca(t){let e=Mn(),r=af(t.source),n=Jr(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var To=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function dg(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Ta(t,e,r){let n=r??{},i=dg(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new To(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:h,abortCode:p}=n;f(new To(h,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function IA(t,e,r){return n=>t(Ta(n,e,r))}function pg(t,e,r){return{sink:IA(t.sink,e,{...r,onAbort:void 0}),source:Ta(t.source,e,r)}}function Ba(t){return t[Symbol.asyncIterator]!=null}var La=t=>{let e=Vt.encodingLength(t),r=Dt(e);return Vt.encode(t,r),La.bytes=e,r};La.bytes=0;function Pa(t,e){e=e??{};let r=e.lengthEncoder??La;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Ba(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Pa.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??La;return new Xe(r(t.byteLength),t)};var ki=J(bl(),1);var RA=8,CA=1024*1024*4,Fn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Fn||(Fn={}));var cf=t=>{let e=Vt.decode(t);return cf.bytes=Vt.encodingLength(e),e};cf.bytes=0;function Bo(t,e){let r=new Xe,n=Fn.LENGTH,i=-1,o=e?.lengthDecoder??cf,s=e?.maxLengthLength??RA,a=e?.maxDataLength??CA;function*c(){for(;r.byteLength>0;){if(n===Fn.LENGTH)try{if(i=o(r),i<0)throw(0,ki.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,ki.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Fn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,ki.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Fn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Fn.LENGTH}}}return Ba(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ki.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ki.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Bo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Bo(n,{...e??{},onLength:o=>{r=o}})};var LA=ie("libp2p:mss"),mg=Y(`
49
49
  `);function Lo(t){let e=new Xe(t,mg);return Pa.single(e)}function qn(t,e,r={}){let n=Lo(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function yg(t,e,r={}){let n=new Xe;for(let i of e)n.append(Lo(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function PA(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>t.next(r)},i=n;e?.signal!=null&&(i=Ta(n,e.signal));let o=a=>{r=a},s=await Un(i,a=>Bo(a,{onLength:o,maxDataLength:1024}),async a=>Aa(a));if(s==null||s.length===0)throw new E("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==mg[0])throw LA.error("Invalid mss message - missing newline - %s",s.subarray()),new E("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function Oi(t,e){let r=await PA(t,e);return ee(r.subarray())}var Po=ie("libp2p:mss:select");async function Do(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=Ca(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");Po.trace('select: write ["%s", "%s"]',Cr,a);let c=Y(Cr),u=Y(a);yg(i,[c,u],r);let l=await Oi(n,r);if(Po.trace('select: read "%s"',l),l===Cr&&(l=await Oi(n,r),Po.trace('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){Po.trace('select: write "%s"',f),qn(i,Y(f),r);let h=await Oi(n,r);if(Po.trace('select: read "%s" for "%s"',h,f),h===f)return o(),{stream:s,protocol:f}}throw o(),new E("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var No=ie("libp2p:mss:handle");async function ko(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=Ca(t);for(;;){let a=await Oi(i,r);if(No.trace('read "%s"',a),a===Cr){No.trace('respond with "%s" for "%s"',Cr,a),qn(n,Y(Cr),r);continue}if(e.includes(a))return qn(n,Y(a),r),No.trace('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){qn(n,new Xe(...e.map(c=>Lo(Y(c)))),r),No.trace('respond with "%s" for %s',e,a);continue}qn(n,Y("na"),r),No('respond with "na" for "%s"',a)}}var bg=J($n(),1);var xg=Symbol.for("@libp2p/connection");var Da=ie("libp2p:connection"),NA=500,uf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,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._newStream=i,this._close=o,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[xg]=!0;get streams(){return this._getStreams()}async newStream(e,r){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&&r?.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){Da("closing connection to %a",this.remoteAddr),this.status="closing",e.signal=e?.signal??AbortSignal.timeout(NA);try{(0,bg.setMaxListeners)?.(1/0,e.signal)}catch{}try{await Promise.all(this.streams.map(async r=>r.close(e))),await this._close(e),this.timeline.close=Date.now(),this.status="closed"}catch(r){Da.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){Da.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),Da.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function wg(t){return new uf(t)}var Be=ie("libp2p:upgrader");function OA(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return nf}function MA(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??of}function Eg(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var Na=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new E(`The multiaddr connection is blocked by gater.${n}`,F.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",F.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=Di([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,lf.setMaxListeners)?.(1/0,u)}catch{}try{let l=pg(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",F.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),Be("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(Be("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(o,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new E("inbound connection that skipped encryption must have a peer id",F.ERR_INVALID_MULTIADDR);let p=pe(h);c="native",o=p}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,s=h.stream}}catch(h){throw Be.error("Failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),Be("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o,transient:r?.transient})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=pe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),Be("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(o=l,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...o};await this.shouldBlockConnection(s,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new E("Encryption was skipped but no peer id was passed",F.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...o},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw Be.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),Be("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await ko(d,m);if(Be("%s: incoming stream opened on %s",n,g),f==null)return;let x=OA(g,this.components.registrar);if(Eg(g,"inbound",f)===x){let C=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,F.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(C),C}d.source=y.source,d.sink=y.sink,d.protocol=g,await this.components.peerStore.merge(s,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,f),this._onStream({connection:f,stream:d,protocol:g})}).catch(async m=>{Be.error(m),d.timeline.close==null&&await d.close()})}}),l=async(d,m={})=>{if(u==null)throw new E("Stream is not multiplexed",F.ERR_MUXER_UNAVAILABLE);Be("%s: starting new stream on %s",n,d);let y=await u.newStream();try{if(m.signal==null){Be("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),m.signal=AbortSignal.timeout(3e4);try{(0,lf.setMaxListeners)?.(1/0,m.signal)}catch{}}let{stream:g,protocol:x}=await Do(y,d,m),w=MA(x,this.components.registrar,m);if(Eg(x,"outbound",f)>=w){let _=new E(`Too many outbound protocol streams for protocol "${x}" - limit ${w}`,F.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(_),_}return await this.components.peerStore.merge(s,{protocols:[x]}),y.source=g.source,y.sink=g.sink,y.protocol=x,this.components.metrics?.trackProtocolStream(y,f),y}catch(g){throw Be.error("could not create new stream",g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new E(String(g),F.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(d=>{Be.error(d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(f!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){Be.error(m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{Be.error(m)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let p=()=>{throw new E("connection is not multiplexed",F.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=wg({remoteAddr:i.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async d=>{await i.close(d),u!=null&&await u.close(d)},abort:d=>{i.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o,options:s}=this.components.registrar.getHandler(i);if(r.transient&&s.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());Be("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await ko(e,r,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return Be("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new E(String(n),F.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());Be("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await Do(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return Be("encrypting outbound connection to %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw new E(String(i),F.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());Be("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await Do(e,n,{writeBytes:!0});Be("%s selected as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Be.error("error multiplexing outbound stream",i),new E(String(i),F.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());Be("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await ko(e,n,{writeBytes:!0}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw Be.error("error multiplexing inbound stream",i),new E(String(i),F.ERR_MUXER_UNAVAILABLE)}}};var pt=ie("libp2p"),ff=class extends co{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new co,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new _u(c.type,{detail:c.detail}));return u||l};try{(0,vg.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=$m({peerId:e.peerId,events:r,datastore:e.datastore??new aa,connectionGater:Jm(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new ia(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{if(c.detail.previous==null){let u={id:c.detail.peer.id,multiaddrs:c.detail.peer.addresses.map(l=>l.multiaddr),protocols:c.detail.peer.protocols};this.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Na(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Ra(this.components,e.transportManager)),this.configureComponent("connectionManager",new ba(this.components,e.connectionManager)),this.configureComponent("registrar",new Ia(this.components)),this.configureComponent("addressManager",new ca(this.components,e.addresses));let o=Tn.generateOptions();this.keychain=this.configureComponent("keyChain",new Tn(this.components,{...o,...e.keychain}));let s=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Sa(this.components,{routers:s}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new _a(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){pt.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[Eu]!=null&&(pt("registering service %s for content routing",c),a.push(l[Eu])),l[Su]!=null&&(pt("registering service %s for peer routing",c),s.push(l[Su])),l[Au]!=null&&(pt("registering service %s for peer discovery",c),l[Au].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&pt.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,pt("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(pt("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),pt("libp2p has started")}catch(r){throw pt.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(pt("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),pt("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Bn;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new E("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new E("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){Ln(e)&&(e=pe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(pt("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Me([Y("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return so(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){pt.error(new Error(F.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{pt.error(n)})}};async function _g(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new Tn({datastore:e},zr(Tn.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await Mp()),new ff(cy(t))}async function UA(t){let e=await _g(t);return t.start!==!1&&await e.start(),e}return Mg(KA);})();
50
50
  /*! Bundled license information:
51
51